[英]React Native: changing state via external function doesn't rerender
I've created a function as per need to change state only if it's not the same value as before (ie toggle if not same). 我已经根据需要创建了一个仅在状态值与以前不相同时更改状态的函数(即,如果不相同则进行切换)。 However, it doesn't rerenders the components.
但是,它不会重新提供组件。 Can someone let me know what I'm doing wrong?
有人可以让我知道我在做什么错吗? It does change the state though.
它确实会改变状态。
export function toggleState(thi_s, k, new_v)
{
if(thi_s.state[k]!=new_v)
{
thi_s.state[k] = new_v;
return true;
}
return false;
}
. 。 .
。
[usage] [用法]
if(this.state.xyz!=true) this.setState({xyz:true}); //does rerender as expected
. 。
toggleState(this, 'xyz', true); //doesn't rerenders
The state is changed without rerending, and I can check it using console.log
right after the call 状态更改后无需重新发送,我可以在通话后立即使用
console.log
进行检查
In toggleState
you're not calling setState
and are mutating the state directly, which you should never do and is also the reason why a re-render is not triggered: 在
toggleState
您不是在调用setState
而是在直接改变状态,这是您永远都不应做的,也是未触发重新渲染的原因:
thi_s.state[k] = new_v;
Change that to 更改为
thi_s.setState({[k]: new_v});
Also, instead of passing this
to toggleState
you should consider using an arrow function or .bind(this)
instead so that you can reference this
inside of the function w/o passing it as an argument. 此外,而不是通过
this
来toggleState
你应该考虑使用箭头功能或.bind(this)
,而不是让你可以参考this
函数的内部W / O将它作为一个参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.