【问题标题】:Access state present in functional component in reducer访问状态存在于减速器的功能组件中
【发布时间】:2021-01-19 10:47:12
【问题描述】:

我有两种状态要维护:

  1. 包含要显示的项目列表的数组
  2. 一个整数(称为索引),表示当前显示数组中的哪些元素。

对于数组,我使用 useReducer 钩子来添加、删除、编辑数组中的元素。 reducer 函数写在函数组件之外。

在这个 reducer 中,我想访问“索引”状态的状态值以了解要修改哪个元素。但是,由于这种状态是在功能组件内。如何做到这一点?

这里是示例代码:

function reducer(state, action){
    // Reducer code here
}

function SomeComponent(props){
    [allItems, dispatch] = useReducer(reducer,[])
    [index,setIndex] = useState(null)
    // Use the above index within the reducer
}

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    你需要像这样传入 dispatch 函数:

      switch (action.type) {
        case SET_VISIBILITY_FILTER:
          return state.filter(data => data.id === action.index) //check here
        default:
          return state
      }
    
    
    

    你可以从你的组件中调度这个事件:

    
    function SomeComponent(props){
        [allItems, dispatch] = useReducer(reducer,[])
        [index,setIndex] = useState(null)
        useEffect(() => {
       dispatch({ type: 'SET_VISIBILITY_FILTER',index:index })
    },[index]] //it will run when index changes
    }
     
    
    

    我建议在reducer 中设置索引,这样可以轻松跟踪来自单一来源的所有数据

    【讨论】:

      【解决方案2】:
      const initialState = 0;
          const reducer = (state, action) => {
            switch (action) {
              case 'increment': return state + 1;
              case 'decrement': return state - 1;
              case 'reset': return 0;
              default: throw new Error('Unexpected action');
            }
          };
      

       const YourComponent = () => {
            const [count, dispatch] = useReducer(reducer, initialState);
            return (
              <div>
                {count}
                <button onClick={() => dispatch('increment')}>+1</button>
                <button onClick={() => dispatch('decrement')}>-1</button>
                <button onClick={() => dispatch('reset')}>reset</button>
              </div>
            );
          };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-20
        • 1970-01-01
        • 1970-01-01
        • 2019-04-11
        • 2017-07-03
        • 2021-04-15
        • 1970-01-01
        • 2021-12-22
        相关资源
        最近更新 更多