简体   繁体   中英

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).

Essentially, I need to set the visible state, and others, on success/error of certain calls that are being made in my app. These calls are made in a separate js file where this.setState({}) doesn't just work .

I've set up an example here: 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. 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 . 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.

You can not just call this.setState({}) from anywhere, think about what is 'this' in that context.

In the randomjsfile.js, this might be window the global context. 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.

Something like this: How to update parent's state in React?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM