componentWillReceiveProps not firing

前端 未结 4 2175
醉梦人生
醉梦人生 2021-02-18 12:51

In my other classes, componentWillReceiveProps was working nicely, but for some reason, it isn\'t firing here.

ItemView.jsx

class ItemView extends React.         


        
相关标签:
4条回答
  • 2021-02-18 13:30

    If anyone else is having a problem with this...

    componentWillReceiveProps will not be called if you are receiving the exact same props as before. What you can do to get around it is add a dummy prop that iterates every time you want to send the same prop to the component in case that component internally resets itself somehow

    click() {
        this.setState({counter: ++this.state.counter, unchangingProp:true})
    }
    <Component unchangingProp={this.state.unChangingProp} counter={this.state.counter}/>
    

    This way componentWillRecieveProps will be triggered every time.

    0 讨论(0)
  • 2021-02-18 13:33

    i also had the same problem. if someone typed in a direct url the componentwillreceiveprops did not fire. i had to refactor my code as well to get it all working.

    Changes i made was in my initial index.tsx having something like (i.e. have the router as the outer element):

    render( 
    <Router history={hashHistory} >
    {routes}
    </Router>
    , document.getElementById('root'));

    my default route was to my app.tsx page with a structure as follows: render() {

    return (
     <Provider store={store}>
       <div id="appContainer">
               {this.props.children}
       </div>
     </Provider>
    );
    

    }

    0 讨论(0)
  • 2021-02-18 13:35

    After much painful debugging, I found out that the problem was that ItemView was being called inside a modal (react-bootstrap) which for some reason, doesn't support componentWillReceiveProps(). Ended up fixing the issue by refactoring the code. Thanks guys!

    0 讨论(0)
  • 2021-02-18 13:45

    In my case my component was being re-created every render, so I had to put my logic in the constructor. I know its not ideal but it was a simple component and was easier for me to do than try to fix the issue that was causing the component to get re-created each time.

    0 讨论(0)
提交回复
热议问题