Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.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 在何处存储从React中的props计算的值_Javascript_Reactjs_Single Page Application - Fatal编程技术网

Javascript 在何处存储从React中的props计算的值

Javascript 在何处存储从React中的props计算的值,javascript,reactjs,single-page-application,Javascript,Reactjs,Single Page Application,我在render()中使用了React道具,但不想在每次render()执行该道具,存储昂贵计算结果的最佳位置是哪里 constructor(props) { super(props) const result = this.doExpensiveCalculation(props) } componentWillReceiveProps(nextProps) { // if nextProps differ from props const result =

我在
render()
中使用了React道具,但不想在每次
render()执行该道具,存储昂贵计算结果的最佳位置是哪里

constructor(props) {
    super(props)
    const result = this.doExpensiveCalculation(props)
}

componentWillReceiveProps(nextProps) {
    // if nextProps differ from props
    const result = this.doExpensiveCalculation(nextProps)
}

doExpensiveCalculation(props) {
   // Some expensive stuff 
}

render(){
    // Use doExpensiveCalculation(this.props) here
}
选项是
this
state
,但我认为两者都不令人满意。是否有现成的使用回忆录的解决方案


另一方面,我应该担心优化这个吗?我了解到React可以重新渲染组件,即使道具没有更改,但这种情况是否经常发生?

您可以在
shouldComponentUpdate
的生命周期方法中处理重新渲染。默认值总是
返回true
。通过返回false,React将不会重新渲染组件

看。此外,由于道具是只读的,因此仅当状态发生更改时,React才会更新


您可以选择按建议存储它,或者使用带有静态字段的类将其保存在那里。

您可以在
shouldComponentUpdate
的生命周期方法中处理重新呈现。默认值总是
返回true
。通过返回false,React将不会重新渲染组件

看。此外,由于道具是只读的,因此仅当状态发生更改时,React才会更新


您可以选择按建议存储它,或者让一个带有静态字段的类将其保存在那里。

如果您只想在获得新道具时执行昂贵的计算,而不是在每次渲染时,您可能需要:

componentWillReceiveProps()
在安装的组件接收新的道具之前被调用

至于存储它们的位置,您可以将它们存储在state中,也可以将它们作为属性直接存储在组件实例上。这两种方法都同样有效

但是,您需要确保比较值,以避免不必要的重新计算

例如:

componentWillReceiveProps(nextProps) {
    if (nextProps.someValue !== this.props.someValue) {
        this.someResult = this.performExpensiveCalculation(nextProps.someValue);
    }
}

如果您只想在获得新道具时执行昂贵的计算,而不是在每次渲染时执行,则可能需要:

componentWillReceiveProps()
在安装的组件接收新的道具之前被调用

至于存储它们的位置,您可以将它们存储在state中,也可以将它们作为属性直接存储在组件实例上。这两种方法都同样有效

但是,您需要确保比较值,以避免不必要的重新计算

例如:

componentWillReceiveProps(nextProps) {
    if (nextProps.someValue !== this.props.someValue) {
        this.someResult = this.performExpensiveCalculation(nextProps.someValue);
    }
}

此解决方案无法解决某些数据更改应更新组件但不应重新计算值的情况。该值必须保存在某个位置。此解决方案无法解决某些数据更改应更新组件但不应重新计算该值的情况。必须将该值保存在某个位置。您应该将
结果
保存为状态。如果可能,
doExpensiveCalculation
应该以异步方式完成。如果您使用的是redux和redux saga之类的软件,这应该很简单。您应该将
result
保存在state中。如果可能,
doExpensiveCalculation
应该以异步方式完成。如果您使用的是redux和redux saga之类的东西,那么这应该很简单。