警告:_renderNewRootComponent():渲染方法应该是props和state的纯函数;

时间:2017-08-14 05:38:12

标签: javascript reactjs ecmascript-6 es6-class

我尝试运行类Buttons,将值传递给方法visibilityFilter(value){...}并获取错误

Warning: _renderNewRootComponent(): Render methods should be a pure function of props and state; 
triggering nested component updates from render is not allowed. 
If necessary, trigger nested updates in componentDidUpdate. 
Check the render method of Buttons.

我的代码如下:

class Buttons extends React.Component {
    visibilityFilter(value){
        let action = {type: 'set_visibility_filter',payload: {name: value, on: true}};
        store.dispatch(action);
    };
    render(){           
        return(
            <div className="container-fluid">
                <div className="row">
                    <div className="col-lg-4 col-md-4 col-sm-4 col-xs-0">
                        <buttom type="button" className="m-t-1-em w-100 btn btn-info" onClick={this.visibilityFilter('favorite')} >Favorite</buttom>
                    </div>
                </div>              
            </div>
        );
    };
};  

问题是什么以及如何将值传递给方法?

2 个答案:

答案 0 :(得分:0)

你需要在onClick =(...)中的方法之后摆脱(),使用非标准的html属性,并在事件对象的帮助下重写代码,如下所示:

class Buttons extends React.Component {
    visibilityFilter(event){
        let action = {type: 'set_visibility_filter',payload: {name: event.target.dataset.filterName, on: true}};
        store.dispatch(action);
        console.info(' event.target.dataset.filterName:',event.target.dataset.filterName);
    };
    render(){           
        return(
            <div className="container-fluid">
                <div className="row">
                    <div className="col-lg-4 col-md-4 col-sm-4 col-xs-0">
                        <buttom type="button" className="m-t-1-em w-100 btn btn-info" onClick={this.visibilityFilter} data-filter-name="favorite">Favorite</buttom>
                    </div>
                </div>              
            </div>
        );
    };
};

希望它会有所帮助。

答案 1 :(得分:0)

看起来您正在立即调用visibilityFilter()函数。调用render()方法然后调用visibilityFilter()函数,该函数执行更改状态的调度,然后重新呈现。渲染方法中的任何内容都不应改变您的状态。

相反,onClick应该是这样的。 //print_r($dose);

然后,您可以使用点击处理程序中的参数onClick={this.visibilityFilter.bind(this, 'favorite')}作为第一个参数。