reactjs - 在哪里调用 setState 来获取 redux 值?

标签 reactjs react-native redux react-redux

我对 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/

相关文章:

image - 我如何在 React Native 中实际使用 Image.capInsets?

javascript - React Native 版本不匹配。无法在Android Studio中生成构建,但通过VS代码react-native run-android可以正常运行

javascript - Redux-Form matchDispatchToProps 不工作

Reactjs map 函数 - 迭代 json 对象

javascript - React 复选框 - Onchange 复选框,第一次未定义

javascript - 如何避免由于 React-Native 中未定义而出现错误

reactjs - Redux ConnectedProps 类型为 never

javascript - 在 redux 中使用不可变 js(toJS 和 from JS)的正确方法

node.js - 我可以改变 Recoil Atom Effect 中的其他状态吗

javascript - 父组件中的 Reactjs 按钮在子组件中提交 Redux 表单