[英]Function is not called when state is changed
I have a function in react showPeople.我在 react showPeople 中有一个 function。 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.稍后在组件中,我想将其称为 function,以便向我展示一些工人的信息。 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.当我更改 state 时,它不会被调用。 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 ).正如本文所写,它应该在state更新时更新(参见此处的示例)。 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.除非您保存了数组workers
,例如const {workers} = this.state
或const [workers, setWorkers] = useState([{'id': '1', role: 'thisRoleNAme'}])
那么你可能不会实际上正在访问一块 state。
Edit your function to accept workers as parameter:编辑您的 function 以接受工人作为参数:
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.并从 state 传递工人。
<div>
{showPeople(this.state.workers)}
</div>
It should re-render whenever your this.state.workers change and it will render with new workers.每当您的 this.state.workers 更改时,它都应该重新渲染,并且它将与新的工人一起渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.