首页 > 解决方案 > 反应:儿童内部的状态不通过道具更新

问题描述

我想使用道具设置子组件的状态值,然后为相应的表单字段显示相同的值。我在 componentDidMount() 中做到了,但它不起作用。

代码:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tweetCount: this.props.tweetCount
    };
  }

  componentDidMount() {
    const tweetCount = this.props.tweetCount;
    this.setState({ tweetCount });
  }

  render() {
    return (
      <React.Fragment>
        <Form>
          <FormGroup>
            <Label for="tweetCount">
              Tweets per Column (between 1 and 30):
              {this.state.tweetCount}
            </Label>
            <Input
              id="tweetCount"
              type="range"
              min="1"
              max="30"
              value={this.state.tweetCount}
              onChange={this.changeTweetCount}
              step="1"
            />
          </FormGroup>
        </Form>
      </React.Fragment>
    );
  }
}

标签: reactjsreact-bootstrap

解决方案


如果您使用版本高于 16.3 的 React,则getDerivedStateFromProp在 usingcomponentDidMountcomponentWillReceiveProps使用以下代码中使用 so:

static getDerivedStateFromProps(props, state)
{
  return{
    tweetCount:props.tweetCount
  }
}

推荐阅读