我对 react native 和异步编程还很陌生,并试图了解如何“同步”redux 状态值和本地状态值。
例如,我有一个文本字段“aboutMe”存储在服务器端,并使用mapStateToProps将其放入 Prop 中:
const mapStateToProps = (state) => {
return { aboutMe: state.aboutMe };
}
在渲染中,我正在使用一个 TextInput,以便用户可以编辑此字段,并且我想默认为服务器端保存的内容:
<TextInput
onChangeText={(aboutMe) => {
this.setState({aboutMe});
}}
value={this.state.aboutMe}
/>
基本上,我需要调用某个地方
this.setState({ aboutMe: this.props.aboutMe });
哪里是正确的地方?我试图使用 componentWillReceiveProps,但该生命周期方法不会在构造函数上调用,因此我需要 setState 两次(在构造函数和 componentWillReceiveProps 中)。
还有其他方法可以做到这一点吗?我觉得这是一个非常普遍的问题,很多 React Native 开发人员已经解决了,但我在网上找不到普遍接受的方法。
谢谢!
编辑:
我有很多 TextInput,因此我有一个单独的按钮来调用保存变量的操作:
<Button onPress={()=>{
this.props.saveUserInput(this.state.aboutMe,
this.state.name, this.state.address, ....}}>
<Text> Save changes </Text>
</Button>
从评论中,我了解到可以调用 onChangeText 的保存操作...但是来回流量是否太多?将所有变量本地保存到状态然后立即调用所有内容的保存会更好吗?另外,如果用户想“取消”而不是保存怎么办?更改是否已保存,我们将无法放弃更改?
最佳答案
1) 如果您的组件是受控组件(您需要其中的状态)并且请求是异步的,那么您必须在 componentWillReceiveProps
中设置状态像这样:
class ExampleComp extends Component {
constructor(props) {
super(props);
this.state = {
aboutMe: ""
}
}
componentWillReceiveProps(nextProps) {
this.setState({
aboutMe: nextProps.aboutMe,
});
}
render() {
return (
<TextInput
onChangeText={(aboutMe) => {
this.setState({aboutMe});
}}
value={this.state.aboutMe}
/>
);
}
}
请记住,这里的关键是,从现在开始,国家必须保持唯一的事实来源。
2) 另一种选择是,您可以等到父组件中的请求完成,然后设置 aboutMe
在你的构造函数中,这样你就可以避免 componentWillReceiveProps
。例如:
class ParentComp extends Component {
render() {
return (
<div>
{this.props.aboutMe && <ExampleComp/>}
</div>
);
}
}
class ExampleComp extends Component {
constructor(props) {
super(props);
this.state = {
aboutMe: props.aboutMe
}
}
render() {
return (
<TextInput
onChangeText={(aboutMe) => {
this.setState({aboutMe});
}}
value={this.state.aboutMe}
/>
);
}
}
这样做的缺点是在请求完成之前不会显示文本输入。
关于reactjs - 在哪里调用 setState 来获取 redux 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49562515/