Javascript this.setState是否未覆盖旧状态?

Javascript this.setState是否未覆盖旧状态?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我试图覆盖一些我存储在状态中的错误标签,但我一辈子都不明白为什么它没有覆盖我提供的密钥: if(this.state.viewState === 'STEP_1') { if (!this.isValidAmount(totalAmountPaid.value)) { totalAmountPaid.errorLabel = 'Incorrect Amount'; this.setState({ totalAmountPaid, errorLabel:

我试图覆盖一些我存储在状态中的错误标签,但我一辈子都不明白为什么它没有覆盖我提供的密钥:

if(this.state.viewState === 'STEP_1') {
  if (!this.isValidAmount(totalAmountPaid.value)) {
    totalAmountPaid.errorLabel = 'Incorrect Amount';
    this.setState({
      totalAmountPaid,
      errorLabel: 'invalid or missing total amount'
    });
    return;
  };

  if (!this.isValidAmount(amountToBeClaimed.value)) {
    amountToBeClaimed.errorLabel = 'Incorrect Amount';
    console.log('invalidClaimAmount');
    this.setState({
      amountToBeClaimed,
      errorLabel: 'invalid or missing claim amount'
    });
    return;
  };

  if(amountToBeClaimed.value > totalAmountPaid.value) {
    this.setState({ errorLabel: 'claims cannot be greater than total amount paid' });
    return;
  };

  this.setState({ ...this.state, errorLabel: 'asdads' })
};
除了最后一个,所有的setState调用都有效

this.setState({…this.state,errorLabel:'asdads'})

感谢您的帮助

编辑 如果我在setState的末尾添加一个return语句,setState就可以工作,但是当然,它不允许我继续

if(this.state.viewState === 'STEP_1') {
  if (!this.isValidAmount(totalAmountPaid.value)) {
    totalAmountPaid.errorLabel = 'Incorrect Amount';
    this.setState({
      totalAmountPaid,
      errorLabel: 'invalid or missing total amount'
    });
    return;
  };

  if (!this.isValidAmount(amountToBeClaimed.value)) {
    amountToBeClaimed.errorLabel = 'Incorrect Amount';
    console.log('invalidClaimAmount');
    this.setState({
      amountToBeClaimed,
      errorLabel: 'invalid or missing claim amount'
    });
    return;
  };

  if(amountToBeClaimed.value > totalAmountPaid.value) {
    console.log('in amount greater than total if')
    this.setState({ errorLabel: 'claims cannot be greater than total amount paid' });
    return;
  };

  this.setState({ ...this.state, errorLabel: '' });
  return;
};
*完整的代码片段*

  goToNext = () => {
const { totalAmountPaid, amountToBeClaimed } = this.state.inputs;

if(this.state.viewState === 'ADD_RECEIPT' && this.state.receiptedAdded === true) {
  console.log('in add receipt if')
  let newState = this.state;
  this.setState({
    ...newState,
    viewState: 'STEP_2',
    header: 'Enter Item Details',
    subHeader: "For each item we'll need further information.",
    isFormCompleted: {
      STEP_1: true,
      STEP_2: false
    },
    errorLabel: 'sdadasds'
  }, () => this.saveClaim('STEP_1'));
} else if (this.state.viewState === 'ADD_RECEIPT' && this.state.receiptedAdded === false) {
  this.selectReceipt();
};

if(this.state.viewState === 'STEP_1') {
  if (!this.isValidAmount(totalAmountPaid.value)) {
    totalAmountPaid.errorLabel = 'Incorrect Amount';
    this.setState({
      totalAmountPaid,
      errorLabel: 'invalid or missing total amount'
    });
    return;
  };

  if (!this.isValidAmount(amountToBeClaimed.value)) {
    amountToBeClaimed.errorLabel = 'Incorrect Amount';
    console.log('invalidClaimAmount');
    this.setState({
      amountToBeClaimed,
      errorLabel: 'invalid or missing claim amount'
    });
    return;
  };

  if(amountToBeClaimed.value > totalAmountPaid.value) {
    console.log('in amount greater than total if')
    this.setState({ errorLabel: 'claims cannot be greater than total amount paid' });
    return;
  };

  // //doesnt work????
  // if(amountToBeClaimed.value > this.props.accountBalance) {
  //   this.setState({ errorLabel: 'claims cannot be greater than total account balance' });
  //   return;
  // };

  this.setState({ errorLabel: '' });
};

if(this.state.viewState === 'STEP_2') {
  console.log('in step 2 if');
  if(this.state.inputs.itemOneMajorCategory.value === '') {
    this.setState({ errorLabel: 'Please choose an item category' });
    return;
  };
  if(this.state.inputs.itemOneDocumentaryEvidence.value === '') {
    this.setState({ errorLabel: 'Please provide documentary evidence' });
    return;
  };
  this.setState({ errorLabel: '' });
};

switch (this.state.viewState) {
  case 'STEP_1': 
    let newState = this.state;
    newState.inputs.numberOfItems.value = 1; //for Stage we are doing one item only
      const item = `item${inWords(newState.inputs.numberOfItems.value, 'startCase')}`;
      newState.inputs[`${item}PersonName`] = {
        type: 'generic',
        displayValue: this.props.personFullName,
        value: this.props.personGuid
      };
      newState.inputs[`${item}MajorCategory`] = {
        //optional: true,
        type: 'generic',
        value: '',
        displayValue: '',
        claimCategoryType: ''
      };
      newState.inputs[`${item}ClaimHealthItemGuid`] = {
        optional: true,
        type: 'generic',
        value: '',
        displayValue: '',
      };
      newState.inputs[`${item}AmountPaid`] = {
        //optional: true,
        type: 'generic',
        value: '$',
        formatter: 'currency-new'
      };
      newState.inputs[`${item}DocumentaryEvidence`] = {
        optional: true,
        type: 'generic',
        value: '',
        displayValue: 'Documentary Evidence',
        rightImage: Images.addReceipt
      };
    this.setState({
      ...newState,
      viewState: 'ADD_RECEIPT',
      header: 'Enter Item Details',
      subHeader: "For each item we'll need further information.",
      isFormCompleted: {
        STEP_1: true,
        STEP_2: false
      },
      errorState: false,
    }, () => this.saveClaim('STEP_1'));
    break;
  case 'STEP_2':
    if (!this.hasUserSelectedCheckbox) {
      return;
    }
    /*this.setState({
      viewState: 'STEP_3',
      header: 'Review',
      subHeader: 'If all looks good, submit for adjudication.',
      isFormCompleted: {
        STEP_1: true,
        STEP_2: true
      }
    });*/
    this.saveClaim('STEP_2');
    break;
  case 'STEP_3':
    if (!this.hasUserSelectedCheckbox) {
      return;
    }
    this.saveClaim('STEP_3');
    Actions.claimSubmissionEnd({inputs: this.state.inputs});
    break;
  case 'STEP_4':  
    if (!this.hasUserSelectedCheckbox) {
      return;
    }
    this.saveClaim('STEP_4');
    Actions.claimSubmissionEnd({inputs: this.state.inputs});
    break;
}

})

如果要使用this.state更新您的状态,请尝试改用setState回调:

this.setState((prevState) => { ...prevState, errorLabel: 'asdads' })

如果前三个条件中的任何一个为true,则最后一个set state调用将不会运行。这是因为其他条件中的return语句。我假设您知道这一点,但我想确保您知道这可能是问题所在。您是否尝试首先使用errorlabel集合声明对象,然后设置扩展对象,或者反之亦然?在最终设置状态之前放置控制台日志。有日志吗?如果没有,那么就没有到达最终的设置状态。我只是仔细检查了一下,它通过了所有的If语句。另外,为了测试,我在最后一个
this.setState({…this.state,errorLabel:'asdads')之后添加了一个返回。
它确实改变了状态。但是如果我删除了returnTHIS^^^^^^记住“setState”是异步的,并且在运行您的请求时可能已经有多个请求了,那么它似乎就不会再运行了。“…this.state”语句保存您的初始状态,然后使用该状态,而不考虑在此期间的任何状态更改。