Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 还原程序中功能组件中存在的访问状态_Javascript_Reactjs_React Hooks - Fatal编程技术网

Javascript 还原程序中功能组件中存在的访问状态

Javascript 还原程序中功能组件中存在的访问状态,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我有两个州需要维护: 包含要显示的项目列表的数组 一个整数(称为索引),表示数组中当前显示的元素 对于数组,我使用useReducer钩子在数组中添加、删除和编辑元素。 reducer函数写在功能组件的外部 在这个reducer中,我想访问“index”状态的状态值,以了解要修改的元素。但是,由于此状态在功能组件内。如何做到这一点 以下是示例代码: function reducer(state, action){ // Reducer code here } function Some

我有两个州需要维护:

  • 包含要显示的项目列表的数组
  • 一个整数(称为索引),表示数组中当前显示的元素
  • 对于数组,我使用useReducer钩子在数组中添加、删除和编辑元素。 reducer函数写在功能组件的外部

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

    以下是示例代码:

    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
    }
    

    您需要传入类似以下内容的分派函数:

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

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

    constyourcomponent=()=>{
    const[count,dispatch]=useReducer(reducer,initialState);
    返回(
    {count}
    分派('increment')}>+1
    分派('减量')}>-1
    分派('reset')}>reset
    );
    };
    
     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>
          );
        };