Rea*_*ner 2 reactjs react-native redux react-redux
我是本机和异步编程的新手,试图了解如何“同步” redux状态值和本地状态值。
例如,我在服务器端存储了一个文本字段“ aboutMe”,并使用mapStateToProps将其放置在道具中:
const mapStateToProps = (state) => {
return { aboutMe: state.aboutMe };
}
Run Code Online (Sandbox Code Playgroud)
在渲染中,我有一个TextInput正在使用,以便用户可以编辑此字段,并且我想默认使用服务器端保存的内容:
<TextInput
onChangeText={(aboutMe) => {
this.setState({aboutMe});
}}
value={this.state.aboutMe}
/>
Run Code Online (Sandbox Code Playgroud)
基本上,我需要打电话的地方
this.setState({ aboutMe: this.props.aboutMe });
Run Code Online (Sandbox Code Playgroud)
正确的地方在哪里?我试图使用componentWillReceiveProps,但是未在构造函数上调用该生命周期方法,因此我需要两次setState(在构造函数和componentWillReceiveProps中)。
还有另一种方法吗?我觉得这是一个非常普遍的问题,许多本机开发人员已解决了这些问题,但我找不到一种普遍接受的在线方式。
谢谢!
编辑:
我有很多TextInputs,所以我有一个单独的按钮来调用操作以保存变量:
<Button onPress={()=>{
this.props.saveUserInput(this.state.aboutMe,
this.state.name, this.state.address, ....}}>
<Text> Save changes </Text>
</Button>
Run Code Online (Sandbox Code Playgroud)
从评论中,我知道可以在saveChangeText上调用save操作...,但是来回的通讯量是否过多?将所有变量本地保存为状态,然后一次调用所有内容的保存方法会更好吗?另外,如果用户想“取消”而不是保存怎么办?更改将已经保存,我们将无法丢弃更改?
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}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
请记住,这里的关键是国家从现在起必须始终是真理的单一来源。
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}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的缺点是,在请求完成之前,不会显示文本输入。
| 归档时间: |
|
| 查看次数: |
5014 次 |
| 最近记录: |