redux的使用

    技术2022-07-10  73

    第一步:先写两个reducer

    todos.js

    const todos = (state = [], action) => { switch (action.type) { // 创建一个 todo case 'ADD_TODO': // 注意,返回不可变数据 return [ ...state, { id: action.id, text: action.text, // title completed: false } ] // 切换一个 todo 的完成状态 case 'TOGGLE_TODO': // 注意,返回不可变数据 return state.map(todo => (todo.id === action.id) ? {...todo, completed: !todo.completed} // 切换完成状态 : todo ) default: return state } } export default todos

    visibilityFilter.js

    const visibilityFilter = (state = 'SHOW_ALL', action) => { switch (action.type) { // 设置显示类型(所有、完成、未完成) case 'SET_VISIBILITY_FILTER': return action.filter // 默认是 SHOW_ALL default: return state } } export default visibilityFilter

    合并reducer,以 index.js 导出

    import { combineReducers } from 'redux' import todos from './todos' import visibilityFilter from './visibilityFilter' const todoApp = combineReducers({ todos, visibilityFilter }) export default todoApp

    第二步:写action

    action.js

    let nextTodoId = 0 // 创建一个 todo export const addTodo = text => { return { type: 'ADD_TODO', id: nextTodoId++, text } } // 设置完成状态 export const setVisibilityFilter = filter => { return { type: 'SET_VISIBILITY_FILTER', filter } } // 切换 todo 完成状态 export const toggleTodo = id => { return { type: 'TOGGLE_TODO', id } }

    第三步:在组件中使用

    import React from 'react' import { connect } from 'react-redux' import { addTodo } from '../actions' // 函数组件,接收 props 参数 let AddTodo = ({ dispatch }) => { // dispatch 即 props.dispatch let input return ( <div> <form onSubmit={e => { e.preventDefault() if (!input.value.trim()) { return } // 创建一个 todo dispatch(addTodo(input.value)) input.value = '' }} > <input ref={node => { input = node }} /> <button type="submit"> Add Todo </button> </form> </div> ) } // connect 高阶组件 ,将 dispatch 作为 props 注入到 AddTodo 组件中 AddTodo = connect()(AddTodo) export default AddTodo
    Processed: 0.027, SQL: 9