嵌套状态的onChangeText和setState不能与提交一起使用

时间:2017-10-02 23:45:15

标签: react-native

对于这个组件,我有两个嵌套状态。

我有一个带有提交按钮的文本输入,如下面的代码所示。

我想在onChangeText触发时在this.state.schoolForm.userInput中保存用户的输入,然后在点击提交按钮时将this.state.schoolForm.userInput保存到this.userInputs.schoolName

当我将setState设置为this.state.userInputValue(一个简单的非嵌套状态)时,这将起作用但是,当我尝试将state设置为嵌套状态时,它不起作用:this.state.schoolForm.userInput

当我点击提交按钮时,没有任何事情发生,但它应该转移到下一个状态。看起来我保存到嵌套状态的方式导致问题,但我已经关注了这篇文章React setState for nested state,我无法从我的代码中发现任何错误。

import React from 'react';
import { StyleSheet, Button, StatusBar, Text, TextInput, View} from 'react-native';

const states = {
  schoolForm: {
    prompt: "Where did you go to school?",
    userInput: "School name",
  },
  durationForm: {
    prompt: "For how long?",
    userInput: "Duration",
  },
}

export default class NewEducation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      //form: states.reviewForm,
      form: states.schoolForm,
      userInputs: {
        schoolName: "",
        duration: ""
      },
      //for testing
      userInputValue: "",
    }
  }

  _nextState = () => {
    switch(this.state.form) {
      case states.schoolForm:
        this.setState({form:states.durationForm});
        break;
      case states.durationForm:
        this.setState({form:states.degreeForm});
        break;
      default:
        break;
    }
  }

  _submitInfo = () => {
    switch(this.state.form) {
      case states.schoolForm:
        //this.setState({ userInputs: { ...this.state.userInputs, schoolName: this.state.form.userInput} });
        this.setState({ userInputs: { ...this.state.userInputs, schoolName: this.state.userInputValue}});
        break;
      case states.durationForm:
        //this.setState({ userInputs: { ...this.state.userInputs, duration: this.state.form.userInput} });
        this.setState({ userInputs: { ...this.state.userInputs, duration: this.state.userInputValue}});
        break;
      default:
        break;
    }
    this._nextState();
  }

  render() {
    return (
      <View style={styles.container}>
        <StatusBar barStyle="light-content"/>
        <Text style={styles.textContentWhite}>{this.state.form.prompt}</Text>

        <TextInput
          style={styles.textContentWhite}
          placeholder={this.state.form.userInput}
          placeholderTextColor="#B7BEDE"
          onChangeText={(userInputValue) => 
            //this.setState({ form: {userInput: userInputValue} }
            this.setState({form: { ...this.state.form, userInput: userInputValue }}
              )}
        />

        <Button
          onPress={this._submitInfo}
          title="Submit"
          color="white"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: "black",
  },

  textContentWhite: {
    fontSize: 20,
    color: 'white',
  },
});

0 个答案:

没有答案