reactjs - 反应:儿童内部的状态不通过道具更新
问题描述
我想使用道具设置子组件的状态值,然后为相应的表单字段显示相同的值。我在 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>
);
}
}
解决方案
如果您使用版本高于 16.3 的 React,则getDerivedStateFromProp
在 usingcomponentDidMount
或componentWillReceiveProps
使用以下代码中使用 so:
static getDerivedStateFromProps(props, state)
{
return{
tweetCount:props.tweetCount
}
}
推荐阅读
- python - 可以将这些冗长的代码更改为递归函数吗?
- sql - 当特定列中的 te 日期值时,如何在 Oracle 中获取昨天的日期?
- kiwi-tcms - 测试计划中缺少“默认组件”选项卡
- python - 为什么熊猫数据框将整数转换为浮点数据类型
- c# - IsConcurrencyToken() 对更新没有影响
- r - 将几个巨大的 .txt 文件 OVER LOOP 读取到 r 中的最快方法
- python - 如何在 Python 中绘制置信区间?
- r - 如何将函数中的参数名称作为列值返回?
- apache-spark - 编写 delta Lake 时使用分区(带 partitionBy)没有效果
- kubernetes - Kubernetes HPA - 如何避免因 CPU 利用率飙升而扩大规模