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

IT技术 javascript reactjs
2021-05-21 23:54:20

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

说:

React.createClass({
    componentWillMount: function() {
        this.computedValue = complexComputing(this.props.feed);
    },
    render: function() {
        return <div>{this.computedValue}</div>
    }
});

你可以看到我直接把 in 放进去computedValuethis,但我不确定它是不是最好的地方。

2个回答

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

React.createClass({
    componentWillMount: function() {
        this.setState({
            computedValue: complexComputing(this.props.feed)
        });
    },
    render: function() {
        return <div>{this.state.computedValue}</div>
    }
});

this如果您只是想在生命周期方法之间共享数据,那么穿上是正确的,最常见的是使组件可用于 componentWillUnmount 中的清理。

对于这些类型的计算,您采用了正确的方法之一。

根据react的组分的生命周期也只有被调用一次且仅一次的一些方法,它们是getInitialState()getDefaultProps()componentWillMount()componentDidMount()

但是我会把它的getDefaultProps(),因为它更有意义,有这种类型的数据的存在,因为它的数据,你通过状态要发生变异。