繁体   English   中英

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

[英]Can I update a component's props in React.js?

在开始使用 React.js 之后, props似乎是静态的(从父组件传入),而state基于事件而变化。 但是,我在文档中注意到对componentWillReceiveProps的引用,其中特别包含以下示例:

componentWillReceiveProps: function(nextProps) {
  this.setState({
    likesIncreasing: nextProps.likeCount > this.props.likeCount
  });
}

这似乎意味着属性可以根据nextPropsthis.props的比较在nextPropsthis.props 我错过了什么? props 是如何变化的,或者我是否误解了它在哪里被调用?

一个组件不能更新它自己的 props,除非它们是数组或对象(即使可能,让组件更新它自己的 props 是一种反模式),但可以更新它的 state 和它的孩子的 props。

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

就在这发生之前,Gauge 的componentWillReceiveProps被调用,以便 Gauge 有机会将新值与旧值进行比较。

道具

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

状态

React 组件应该使用状态来存储组件本身可以更改的信息。

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

当组件的父级再次使用不同的属性渲染组件时,道具可能会发生变化。 我认为这主要是一种优化,因此不需要实例化新组件。

钩子发生了很多变化,例如componentWillReceiveProps变成了useEffect + useRef如这个其他 SO 答案所示),但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,
  },
});

如果您使用recompose ,请使用mapProps从传入的 props 派生出新的 props

编辑例如:

import { compose, mapProps } from 'recompose';

const SomeComponent = ({ url, onComplete }) => (
  {url ? (
    <View />
  ) : null}
)

export default compose(
  mapProps(({ url, storeUrl, history, ...props }) => ({
    ...props,
    onClose: () => {
      history.goBack();
    },
    url: url || storeUrl,
  })),
)(SomeComponent);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM