简体   繁体   中英

Access state present in functional component in reducer

I have two states to maintain:

  1. An array which contains the list of items to display
  2. An integer(called index) that represents which elements within the array is currently displayed.

For the array, I am using the useReducer hook, to add, delete, edit elements within the array. The reducer function is written outside the functional component.

Within this reducer, I want to access the state value of the "index" state to know which element to modify. However, since this state is within the functional component. How to achieve this?

Here is the sample code:

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
}

You need to pass in dispatch function something like this:

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


And you can dispatch this event from your component:


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
}
 

I would suggest set index in reducer as well as it will easy track all data from single source

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM