[英]React: How do I update my components state from an external function?
I've created a notification component (WIP), and when I came to implement it to test it out in a "real" scenario, I realised that I didn't fully understand what I was doing in regards to states (especially outside of the component itself). 我已经创建了一个通知组件(WIP),当我要实现它以在“真实”场景中对其进行测试时,我意识到我不完全了解我对状态所做的事情(尤其是在状态之外)组件本身)。
Essentially, I need to set the visible
state, and others, on success/error of certain calls that are being made in my app. 本质上,我需要根据我的应用中进行的某些调用的成功/错误设置
visible
状态以及其他状态。 These calls are made in a separate js file where this.setState({})
doesn't just work . 这些调用是在单独的js文件中进行的,其中
this.setState({})
不能正常工作 。
I've set up an example here: https://codesandbox.io/s/recursing-ives-ktc4w 我在这里设置了一个示例: https : //codesandbox.io/s/recursing-ives-ktc4w
I've simplified the code. 我简化了代码。 In
randomjsfile.js
I have a timeout that after 2.5 seconds displays a console log AND I would like it to set the visible
state of my component to false. 在
randomjsfile.js
我有一个超时,该超时在2.5秒后显示控制台日志,并且我希望它将组件的visible
状态设置为false。 What I've tried doesn't work, which I guess makes sense because there's nothing that really links them together. 我尝试过的方法不起作用,我认为这是有道理的,因为没有将它们真正联系在一起的东西。 I'm just not sure how to achieve this.
我只是不确定如何实现这一目标。
Any help, or guidance would be really appreciated! 任何帮助或指导将不胜感激!
You can to keep the state in some parent component and pass it as props in child components, or you can use Context or you can use Redux . 您可以将状态保留在某些父组件中,并将其作为道具传递给子组件,或者可以使用Context或Redux 。 As I see your
randomjsfile.js
has nothing to do with React, so, you could use Redux and keep the data in Redux Store, connect your component to this store, and dispatch an action in randomjsfile.js
which will update the store. 如我所见,您的
randomjsfile.js
与React无关,因此,您可以使用Redux并将数据保留在Redux Store中,将组件连接到此存储,然后在randomjsfile.js
调度一个操作,以更新存储。
You can not just call this.setState({}) from anywhere, think about what is 'this' in that context. 您不仅可以从任何地方调用this.setState({}),还可以考虑在这种情况下什么是“ this”。
In the randomjsfile.js, this might be window the global context. 在randomjsfile.js中,这可能是全局上下文的窗口。 You will call those notification from react environment, some other components, which will get to set the state of the top most parent component based on component hierarchy.
您将在react环境和其他一些组件中调用这些通知,这些通知将根据组件层次结构设置最顶层父组件的状态。
Something like this: How to update parent's state in React? 像这样: 如何在React中更新父状态?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.