I have a function in react showPeople. This is the code:
const showPeople = () => {
const people = workers.map((worker, i) => {
return (
<div>
<Worker
id={worker.id}
index={i}
role={worker.role}
/>
</div>
)
})
return people;
}
Later in the component I want to call this function in order to show me some information for the workers. I call it like this:
<div>
{showPeople()}
</div>
And this is ok, but it is called only once. When I change the state it's not called. So I have my updates only after I refresh the page. If i remove the parenthesis in the call, I get nothing on my screen. Does anyone knows what's the problem? Sorry if this question is a duplicate, I am not sure I understood any of the previous answers connected tot his topic. Thanks
As this is written, it should update when state updates ( see example here ). Unless you have the array workers
saved for example like const {workers} = this.state
or const [workers, setWorkers] = useState([{'id': '1', role: 'thisRoleNAme'}])
then you may not actually be accessing a piece of state.
Edit your function to accept workers as parameter:
const showPeople = (workers) => {
const people = workers.map((worker, i) => {
return (
<div>
<Worker
id={worker.id}
index={i}
role={worker.role}
/>
</div>
)
})
return people;
}
And pass workers from state.
<div>
{showPeople(this.state.workers)}
</div>
It should re-render whenever your this.state.workers change and it will render with new workers.
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.