我正在尝试制作一些数据输出依赖于某些外部API的组件。
所以我有这个片段:
class Parent extends Component {
constructor(props) {
super(props)
this.state = {
somethingFromAPI: ''
}
}
componentDidMount() {
/*
something on axios.get() which updates this.state.somethingFromAPI
which normally can have some time delay till executed
*/
}
render() {
return (
<Child value={this.state.somethingFromAPI} />
)
}
}
class Child extends Component {
constructor(props) {
super(props)
this.state = {
value: this.props.value || ''
}
}
handleChange(event) {
this.setState({
value: event.target.value
})
}
static getDerivedStateFromProps(props, state) {
// if difference
return {
value: props.value
}
}
render() {
return (
<div>
<input value={this.state.value} onChange={this.handleChange.bind(this)} />
</div>
)
}
}
ReactDOM.render(
<Parent />
document.getElementById('app')
);
看起来这样工作正常,初始化组件,并获取API数据,之后,输入值似乎更新,这是我所期望的。
令我痛苦的问题是,如果我在输入中键入内容,将调用handleChange,但也会触发此getDerivedStateFromProps,并将使用API中的“旧”替换较新的输入值。
这样做的好方法,也许我一开始就错误地理解应该如何做?指导我正确的方向。
我还不熟悉React。
通常,需要制作可用于新输入或更新现有数据(如某些帖子等)的表单,以便我可以加载API数据。
最好的祝福。
如果使用shouldComponentUpdate
,你是否考虑使用getDerivedStateFromProps
这样的事情可以解决你的问题:
shouldComponentUpdate(nextProps, nextState) {
const { value: nextPropsValue } = nextProps;
const { value: propsValue } = this.props;
const { value } = this.state;
if (nextPropsValue !== propsValue && nextPropsValue !== value) {
this.setState({
value: nextPropsValue
});
}
return value !== nextState.value;
}
更新答案,添加与当前道具值的比较
我认为在这里使用getDerivedStateFromProps
可能是不必要的。如果要在某些情况下阻止渲染,请考虑使用shouldComponentUpdate
https://reactjs.org/docs/react-component.html#shouldcomponentupdate。但听起来你基本上只需要使用输入更改处理程序来保持输入的状态,这是你已经在做的。
您还应该检查this文章,了解为什么有人不应该使用getDerivedStateFromProps
。这是非常有益的。