reactjs – 当属性更改并首次挂载在React上时更改状态 – 缺少功
我遇到一个基于属性的状态的问题。
情景 我有一个组件父项,它创建将属性传递给子组件。 我的问题/问题 如果我从父级接收到一个新的属性,并且我想改变状态,那么只有函数componentWillReceiveProps将被执行,并允许我执行setState。渲染不允许setStatus。 如果我想在开始时设置状态以及收到新属性的时间该怎么办? 这是一个问题,当你的国家高度依赖于你的属性,几乎总是。这可能会变得愚蠢,因为您必须根据新的属性重复要更新的状态。 我的解决方案 我创建了一个新的方法,它在componentWillMount和componentWillReceiveProps上调用。在渲染之前属性已被更新,并且第一次安装了组件之后,我还没有找到任何方法被调用。那么就不需要做这个愚蠢的解决方法了。 无论如何,这里的问题是:当收到或更改新的财产时,是否有更好的选择来更新状态? /*...*/ /** * 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); },/*...*/ 我觉得有点笨,我想我正在失去一些东西 是的,我已经知道了:
我发现这种模式通常不是很有必要。在一般情况下(不总是),我发现基于改变属性的设置状态有点反模式;而是在渲染时简单地导出必要的本地状态。
render: function() { var currentResponses = this.state.candidatesResponses.filter(function (elem) { return elem.questionId === this.props.currentQuestion.id; }); return ...; // use currentResponses instead of this.state.currentResponses } 然而,在某些情况下,缓存该数据(例如可能计算的代价是非常昂贵的)是有意义的,或者您只需要知道何时由于某些其他原因设置/更改道具。在这种情况下,我会基本上使用你在问题中写的模式。 如果你真的不喜欢打字,你可以将这种新方法作为一个混合形式化。例如: var PropsSetOrChangeMixin = { componentWillMount: function() { this.onPropsSetOrChange(this.props); },componentWillReceiveProps: function(nextProps) { this.onPropsSetOrChange(nextProps); } }; React.createClass({ mixins: [PropsSetOrChangeMixin],onPropsSetOrChange: function(props) { var currentResponses = this.state.candidatesResponses.filter(function (elem) { return elem.questionId === props.currentQuestion.id; }); this.setState({ currentResponses: currentResponses,activeAnswer: null }); },// ... }); 当然,如果您使用基于类的React组件,则需要找到一些替代解决方案(例如继承或自定义JS mixins),因为它们现在没有获得React样式的混合。 (对于什么是值得的,我认为代码使用显式方法更清晰;我可能会写这样:) componentWillMount: function () { this.prepareComponentState(this.props); },componentWillReceiveProps: function (nextProps) { this.prepareComponentState(nextProps); },prepareComponentState: function (props) { //set data on state/template var currentResponses = this.state.candidatesResponses.filter(function (elem) { return elem.questionId === props.currentQuestion.id; }); this.setState({ currentResponses: currentResponses,activeAnswer: null }); }, (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |