React: Setting State for Deeply Nested Objects w/ Hooks

后端 未结 2 1385
终归单人心
终归单人心 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:05

    I think you should be using the functional form of setState, so you can have access to the current state and update it.

    Like:

    setState((prevState) => 
      //DO WHATEVER WITH THE CURRENT STATE AND RETURN A NEW ONE
      return newState;
    );
    

    See if that helps:

    function App() {
    
      const [nestedState,setNestedState] = React.useState({
        top_level_prop: [
          {
            nestedProp1: "nestVal1",
            nestedProp2: "nestVal2",
            nestedProp3: "nestVal3",
            nestedProp4: [
              {
                deepNestProp1: "deepNestedVal1",
                deepNestProp2: "deepNestedVal2"
              }
            ]
          }
        ]
      });
    
      return(
        
          
    This is my nestedState:
    {JSON.stringify(nestedState)}
    ); } ReactDOM.render(, document.getElementById('root'));
    
    
    

    UPDATE: With dropdown

    function App() {
      
      const [nestedState,setNestedState] = React.useState({
        propA: 'foo1',
        propB: 'bar'
      });
      
      function changeSelect(event) {
        const newValue = event.target.value;
        setNestedState((prevState) => {
          return({
            ...prevState,
            propA: newValue
          });
        });
      }
      
      return(
        
          
    My nested state:
    {JSON.stringify(nestedState)}
    ); } ReactDOM.render(, document.getElementById('root'));
    
    
    

提交回复
热议问题