我可以在React.js中更新组件的道具吗?

Mat*_*ins 181 javascript properties reactjs

在开始使用React.js之后,看起来似乎props是静态的(从父组件传入),而state基于事件的更改.但是,我在文档中注意到了一个引用componentWillReceiveProps,具体包括这个例子:

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}
Run Code Online (Sandbox Code Playgroud)

这似乎意味着属性可以根据对比nextProps来改变组件this.props.我错过了什么?道具是如何改变的,还是我误解了它被称为何处?

Val*_*éry 223

组件不能更新自己的道具,除非它们是数组或对象(即使可能是反模式,组件更新自己的道具),但可以更新其状态和其子项的道具.

例如,仪表板speed在其状态中具有一个字段,并将其传递给显示此速度的Gauge子项.它的render方法就是return <Gauge speed={this.state.speed} />.当仪表板调用时this.setState({speed: this.state.speed + 1}),将使用新值重新呈现Gauge speed.

就在此之前,Gauge componentWillReceiveProps被调用,因此Gauge有机会将新值与旧值进行比较.

  • 相反的.[documentation](http://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops)说:"当一个组件正在接收新的道具时调用.不会为初始渲染调用此方法". (11认同)
  • 我来自未来:componentWillReceiveProps现在已经过时了,取而代之的是getDerivedStateFromProps和componentDidUpdate的组合。 (4认同)

Ali*_*avi 35

道具

React组件应使用props来存储可以更改的信息,但只能由不同的组件更改.

React组件应使用state来存储组件本身可以更改的信息.

Valéry已经提供了一个很好的例子.

  • @ali_adravi是从某处复制的那些引用?如果是的话,参考是什么?或者那些是你的话,你只是将它们格式化为重点引用? (3认同)

Joo*_*aat 25

当组件的父级使用不同的属性再次呈现组件时,道具可以更改.我认为这主要是一种优化,因此不需要实例化新组件.


Abh*_*mar 5

如果 props 是数组,则更新它们的技巧:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Button
} from 'react-native';

class Counter extends Component {
  constructor(props) {
    super(props);
      this.state = {
        count: this.props.count
      }
    }
  increment(){
    console.log("this.props.count");
    console.log(this.props.count);
    let count = this.state.count
    count.push("new element");
    this.setState({ count: count})
  }
  render() {

    return (
      <View style={styles.container}>
        <Text>{ this.state.count.length }</Text>
        <Button
          onPress={this.increment.bind(this)}
          title={ "Increase" }
        />
      </View>
    );
  }
}

Counter.defaultProps = {
 count: []
}

export default Counter
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
Run Code Online (Sandbox Code Playgroud)

  • 我认为用 props 初始化状态是反模式,应该避免。这是阅读 https://github.com/vasanthk/react-bits/blob/master/anti-patterns/01.props-in-initial-state.md 的好链接。 (6认同)

小智 5

钩子发生了很多变化,例如componentWillReceiveProps变成了useEffect+ useRef如this other SO answer所示),但道具仍然是只读的,所以只有调用者方法应该更新它。