小编bic*_*tll的帖子

属性更改时更改状态并首次挂载React - Missing函数?

我遇到了一个基于属性的状态问题.

场景

我有一个Component父级,它创建一个属性传递给子组件.子组件根据收到的属性做出反应.在React中,改变组件状态的"唯一"正确方法是使用函数componentWillMount或componentDidMount和componentWillReceiveProps,就我所见(其中包括,但让我们关注这些,因为getInitialState只执行一次).

我的问题/问题

如果我从父级接收新属性并且我想要更改状态,则只会执行函数componentWillReceiveProps并允许我执行setState.渲染不允许setStatus.

如果我想在开头设置状态以及收到新属性的时间怎么办?所以我必须在getInitialState或componentWillMount/componentDidMount上设置它.然后,您必须使用componentWillReceiveProps根据属性更改状态.

当您的州高度依赖您的财产时,这是一个问题,这几乎总是如此.哪个可能变得愚蠢,因为你必须根据新属性重复你想要更新的状态.

我的解决方案

我创建了一个新方法,它在componentWillMount和componentWillReceiveProps上调用.我没有找到在渲染之前更新属性之后调用的任何方法,也是第一次安装Component时.然后就没有必要做这个愚蠢的解决方法.

无论如何,这里的问题:当收到或更改新房产时,是否有更好的选择来更新州?

/*...*/
/**
 * To be called before mounted and before updating props
 * @param props
 */
prepareComponentState: function (props) {
    var usedProps = props || this.props;

    //set data on state/template
    var currentResponses = this.state.candidatesResponses.filter(function (elem) {
        return elem.questionId === usedProps.currentQuestion.id;
    });
    this.setState({
        currentResponses: currentResponses,
        activeAnswer: null
    });
},
componentWillMount: function () {
    this.prepareComponentState();
},
componentWillReceiveProps: function (nextProps) {
    this.prepareComponentState(nextProps);
},
/*...*/
Run Code Online (Sandbox Code Playgroud)

我觉得有点愚蠢,我想我已经失去了一些东西......我想还有另一个解决方案可以解决这个问题.

是的,我已经知道了这个:https: //facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

reactjs

25
推荐指数
1
解决办法
2万
查看次数

标签 统计

reactjs ×1