React: Setting State for Deeply Nested Objects w/ Hooks

后端 未结 2 1383
终归单人心
终归单人心 2021-02-08 17:34

I\'m working with a deeply nested state object in React. My code base dictates that we try to stick with function components and so every time I want to update a key/value pair

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-08 18:09

    Another approach is to use the useReducer hook

    const App = () => {      
      const reducer = (state, action) =>{
        return {...state, [action.type]: action.payload}
      }
      
      const [state, dispatch] = React.useReducer(reducer,{
        propA: 'foo1',
        propB: 'bar1'
      });
      
      const changeSelect = (prop, event) => {
        const newValue = event.target.value;
        dispatch({type: prop, payload: newValue});
      }
      
      return(
        
          
    My nested state:
    {JSON.stringify(state)}
    ); } ReactDOM.render(, document.getElementById('root'));
    
    
    

提交回复
热议问题