在输入按钮的第二次或第三次单击时发送POST请求,为什么?

时间:2018-10-28 10:56:33

标签: javascript reactjs react-native react-redux axios

所以我代码中的所有内容都按预期工作,仅在第二次或什至在第三次单击按钮时才发送发帖请求...我猜测这与我更新的方式有关redux状态,但是我的大脑呆滞了,有人可以指出我的错误在哪里吗?

干杯!

class AddressScreen extends Component {
  state = {
    usersNickOrName: "",
    usersAddress: "",
    usersPhoneNumber: ""
  };

  onPressHandler = () => {
    this.props.deliveryInfo(
      this.state.usersNickOrName,
      this.state.usersAddress,
      this.state.usersPhoneNumber
    );

    let uid = this.props.uid;

    axios.post(
      `.../users/${uid}/info.json`,
      {
        nameOrNick: this.props.name,
        address: this.props.address,
        phoneNum: this.props.phoneNum
      }
    );
    this.props.navigator.pop();
  };

  render() {
    return (
      <View style={styles.container}>

        <AnimatedForm delay={100} distance={10}>
          <AnimatedInput
           onChangeText={text => {
              this.setState({ usersNickOrName: text });
            }}
          />
          <AnimatedInput
            onChangeText={text => {
              this.setState({ usersAddress: text });
            }}
          />
          <AnimatedInput
            onChangeText={text => {
              this.setState({ usersPhoneNumber: text });
            }}
          />

          <Animated.View style={styles.buttonView}>
            <TouchableOpacity
              style={styles.button}
              onPress={this.onPressHandler}
            >
              <Text style={{ color: "#fff" }}>Dodaj Info</Text>
            </TouchableOpacity>
          </Animated.View>
        </AnimatedForm>
      </View>
    );
  }
}



const mapStateToProps = state => {
  return {
    name: state.usersNickOrName,
    address: state.usersAddress,
    phoneNum: state.usersPhoneNumber,
    uid: state.userUid
  };
};

const mapDispatchToProps = dispatch => {
  return {
    deliveryInfo: (usersName, usersAddress, phoneNum) =>
      dispatch(deliveryInfo(usersName, usersAddress, phoneNum))
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(AddressScreen);

编辑:

我所做的是,我已将redux更新状态放入componentWillUpdate中,并将其从onPressHandler中删除。现在,它的工作几乎像预期的一样,例如,如果我输入London Str。 36它将发布请求London Str。 3,它不会将最后一个字母或数字发送到服务器...怎么了?

componentWillUpdate() {
    this.props.deliveryInfo(
      this.state.usersNickOrName,
      this.state.usersAddress,
      this.state.usersPhoneNumber
    );
  }

1 个答案:

答案 0 :(得分:0)

根据我在您的实现中看到的内容,the post request将始终由按钮(TouchableOpacity)调用。为防止这种情况发生,您可以采取的措施是实施一项功能,该功能将在尝试触发post request之前检查是否存在正在进行的a new post request