In React, I have a functional component that, upon a child component button ("GenerateButton") being clicked, is supposed to kick off the render of another child component ("UsersView"), which will then display a list of users pulled from a REST API.
While debugging, I'm noticing that even though the "dataShouldLoad" state is toggled to true, it doesn't even try to start loading the code in the "UsersView" component despite "dataShouldLoad" being passed and used as prop. Why is this? What should I do?
Here is my simplified code snippet:
import React, {useState} from 'react';
import GenerateButton from './GenerateButton.js';
import UsersView from './UsersView.js';
export default function GenerateReportView() {
const [dataShouldLoad, setDataShouldLoad] = useState(false);
const [dataHasLoaded, setDataHasLoaded] = useState(false);
const handleGenerateButtonClick = () => {
// By toggling this to true, I am attempting to kick off
// the "UsersView" to fetch its data, and display here
setDataShouldLoad(true);
}
return (
<div>
{dataHasLoaded ?
<UsersView dataShouldLoad={dataShouldLoad} setDataHasLoaded={setDataHasLoaded}/>
: <h2>Click Button to Load</h2>
}
<GenerateButton onClick={handleGenerateButtonClick}/>
</div>
);
}
Right now, the ternary is evaluating dataHasLoaded
, not dataShouldLoad
. Change to dataShouldLoad
and it will render.
When you set new state for useState
hook, the component useState
lies in re-renders and the child components also re-render in general. In your code, UsersView
is not even a child component of GenerateReportView
in DOM, as you put logic- when dataHasLoaded
is false, UsersView
doesn't come as a child component.
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.