Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在ReactJS中,放置由初始传入参数计算一次且不再更改的值的最佳位置是哪里?_Javascript_Reactjs - Fatal编程技术网

Javascript 在ReactJS中,放置由初始传入参数计算一次且不再更改的值的最佳位置是哪里?

Javascript 在ReactJS中,放置由初始传入参数计算一次且不再更改的值的最佳位置是哪里?,javascript,reactjs,Javascript,Reactjs,在reactjs组件中,我将根据传入的参数计算一个值,该参数将不再更改 说: React.createClass({ componentWillMount:function(){ this.computedValue=complexComputing(this.props.feed); }, render:function(){ 返回{this.computedValue} } }); 您可以看到,我已将计算值直接放入此,但我不确定它是否是最佳位置。对于这些类型的计算,您使用的方法是正确的 根

在reactjs组件中,我将根据传入的参数计算一个值,该参数将不再更改

说:

React.createClass({
componentWillMount:function(){
this.computedValue=complexComputing(this.props.feed);
},
render:function(){
返回{this.computedValue}
}
});

您可以看到,我已将
计算值
直接放入
,但我不确定它是否是最佳位置。

对于这些类型的计算,您使用的方法是正确的

根据React组件的生命周期,有一些方法只能被调用一次,它们是
getInitialState()
getDefaultProps()
componentWillMount()
componentDidMount()


不过,我会将它放在
getDefaultProps()
中,因为在那里有这种类型的数据更有意义,因为它是您不希望通过状态进行变异的数据。

经验法则是渲染应该从props和state派生。因为你不能改变你的道具,我会把它放在状态

React.createClass({
    componentWillMount: function() {
        this.setState({
            computedValue: complexComputing(this.props.feed)
        });
    },
    render: function() {
        return <div>{this.state.computedValue}</div>
    }
});
React.createClass({
componentWillMount:function(){
这是我的国家({
computedValue:complexComputing(this.props.feed)
});
},
render:function(){
返回{this.state.computedValue}
}
});

如果您只想在生命周期方法之间共享数据,这是正确的,最常见的方法是在componentWillUnmount中提供可用于清理的内容。

我想要的计算数据基于传入的属性,是否可以在
getDefaultProps
中获取这些数据,从规范:
此外,请注意getDefaultProps()返回的任何复杂对象都将在实例之间共享,而不是复制。我想要的计算值对于所有者实例是不可变的,它不应该被共享。一个好的观点:
渲染应该从props和state派生出来,谢谢!
React.createClass({
    componentWillMount: function() {
        this.setState({
            computedValue: complexComputing(this.props.feed)
        });
    },
    render: function() {
        return <div>{this.state.computedValue}</div>
    }
});