减速器功能组件中存在的访问状态

时间:2020-10-04 11:11:53

标签: javascript reactjs react-hooks

我要维持两种状态:

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

对于数组,我使用useReducer钩子来添加,删除,编辑数组中的元素。 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
}

2 个答案:

答案 0 :(得分:1)

您需要传递调度函数,如下所示:

  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中设置索引,这样可以轻松跟踪来自单一来源的所有数据

答案 1 :(得分:0)

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>
      );
    };