简体   繁体   中英

Parent React component not re-rendering on change state in child using react hooks;

I have a parent component 'HOME' and form for creating a new Pool.I'm sending pool array and setState function into the child component. And if I won't refresh the page parent component won't render a new pool.

"HOME"

  export default function Home() {
  const [user, setUser] = useState({});
  const [lists, setLists] = useState([]);

  useEffect(() => {
      if (!user.id) {
          async function fetchUser() {
              await axios.get('/api/user/')
                  .then(async data => {
                      !!data.data ? (setUser(data.data), setLists(data.data.pools)) : await createUser()
                  }
                  );
          }
          async function createUser() {
              await axios.post('/api/user/')
                  .then(data => { setUser(data.data) });
          }
          fetchUser();
      }
  }, [])
  
  if (user.name) {
      return (
          <div>
              <center><header> Welcome to MyShopper!</header></center>
              <NewPool setter={() => setLists} poolsArr={lists} />
              {lists.length > 0 &&
                  lists.map(pool => (
                      <div id='pools_list' key={pool.id}>
                          <Pools poolInfo={pool} />
                      </div>))
              }
          </div>
      )
  } else {
      return (
          <p>Loading...</p>
      )
  }
}

"POOL"(child)

import axios from 'axios';

export default function NewPool(props){

    const [name,setName]=useState(null);
    const pools=props.poolsArr;
    const setPool=props.setter;

    async function onClickHandler(event){
        event.preventDefault();
        await axios.post('/api/pool/',{poolName:name})
        .then(pool=>{()=>setPool([...pools,pool.data])});   
    }

    function onChangeEv(event){
        setName(event.target.value);
    }

    return(
        <form onSubmit={onClickHandler}>
            <input type="text" id = "name" name="name" 
            onChange={onChangeEv}/>
            <input type="submit" value="AddPool"/>
        </form>
    )
}

I know how to fix it using Redux. Here I want to better understand React Hooks. Is that a bind problem?

I'll be grateful for any advice! Thank you!

Here you're passing the setLists as function reference so setter is a function which returns the setLists reference,

<NewPool setter={() => setLists} poolsArr={lists} />
// using this you'd need to call setter()() to call setLists()

You can directly pass the function like this

<NewPool setter={setLists} poolsArr={lists} />

this should fix your problem

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