简体   繁体   中英

How do I automatically pass updated props in mounted ReactJS component

I have a scenario where in my ReactJS component is mounted on jQuery attach point as below.

In below code CustomfieldsDrawer is a react component and props is the object that I am passing as props. $('#app') is the attach point where my React component will mount.

ReactDOM.render(React.createElement(CustomfieldsDrawer, props), $('#app'));

Now the props object is object that actaually gets updated by ajax call on some customer events, the problem that I am facing is the React component doesn't know when the props get changed and it doesn't automatically rerenders itself. I had to call above line of code again whenever the props is actually changing. Do you guys know a way that can facilitate the auto update for my React component?

Since props is a plain javascript object which was modified outside of React , React doesn't know that it was changed unless you tell it explicitly, in this case by re-rendering the component.

So you can either wrap the code into some parent react component and call the ajax from it and then change it's state to contain the new data which would get passed to the child component and that would trigger automatic re-render.

Or , if you insist on having the code outside of React, you will have to re-render manually. You can however create some handy managing code for this, for inspiration check out ReactDOM.render and the Top Level React API blog post on official React's site.

Also on side note, I am not sure how it's possible that the code you posted works. ReactDOM.render function expects the second parameter to be DOM object, but $('#app') returns jQuery object. Did you mean to have $('#app')[0] there instead?

React component will update itself when we setState for it, so either in the ajax callback, we can setState here, or I think you may use componentWillReceiveProps() for your CustomfieldsDrawer component:

  componentWillReceiveProps(nextProps) {
    this.setState({
      //set you new state here, then in the render method, you should render using this state, instead of props
      someState: nextProps.yourNewProp,
    });
  }

  render() {
    // Use "{this.state.someState}" instead of "{this.props.yourProp}"
    return (
      <div>{this.state.someState}</div>
    );
  }

If this doesn't work yet, please post here your ajax function, or more code, so that I can understand more about your case, then we can fix it together, thanks

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