【问题标题】:Is there a way to ensure a function executes from top to bottom?有没有办法确保函数从上到下执行?
【发布时间】:2019-06-12 04:03:38
【问题描述】:

我正在创建一个图像识别应用,我想使用按钮来改变状态。我已经成功地改变了一些领域,但我遇到了一个奇怪的问题。我将其设置为使用选择器轮选择一个字段,并将其状态值设置为最近按下按钮的文本。然而,五个字段中只有两个按预期更新,尽管所有五个代码块几乎相同。

到目前为止,我已经尝试过移动 setState、在每个 setState 中移动调用、使 onPressHide 函数异步以及大量控制台日志记录。

this.state = {
      selectedItem : 4,
      itemList : ['Serial #', 'Manufacturer', 'Model', 'Model #', 'Manufacture Date'],
      uri : null,
      show : false,
      current : null,
      currentText: "",
      serial: "",
      manufac: "",
      model: "",
      modelNum: "",
      manuDate: "",
      assetId: "",
    };

onPickerSelect (index) {
    this.setState({
        selectedItem: index,
    })
  }

onPressHide() {
    if (this.state.selectedItem == 0) {
      this.setState((state) => ({
        serial: state.currentText,
        show: false,
      }));
      Alert.alert(
        'Update',
        "Serial number will be updated to: " + this.state.currentText,
        [
          {text: 'OK', onPress: () => console.log('OK Pressed')},
        ],
        {cancelable: false},
      );
    }
    if (this.state.selectedItem == 1) {
      this.setState((state) => ({
        manufac: state.currentText,
        show: false,
      }));
      Alert.alert(
        'Update',
        "Manufacturer will be updated to: " + this.state.currentText,
        [
          {text: 'OK', onPress: () => console.log('OK Pressed',)},
        ],
        {cancelable: false},
      );
    }

onPressSubmit() {
    var finalArr = {serial: this.state.serial, manufac: this.state.manufac, model: this.state.model, modelNum: this.state.modelNum, manuDate: this.state.manuDate};
    this.props.updateAll(finalArr);
  }
Data: {Serial: "", Manufacturer: "", Model: "Sonicare", ModelNumber: "", ManufactureDate: ""}

当尝试将 Philips 设置为制造商并将 Sonicare 设置为模型时,最后一行来自服务器控制台日志。上面的 onPressHide 代码中的顶部 if 语句是功能性的,但底部不是。我假设这与 setState 的异步性质有关,但我很困惑为什么它会更新某些字段而不是其他字段。我没有收到任何错误消息,只是输出不正确。任何帮助将不胜感激!

【问题讨论】:

  • 函数总是从上到下执行,没有例外。异步调用会将一个项目添加到队列中。在你的情况下,我什至没有看到 state.selectedItem 发生变化,所以我不知道你为什么期望两个 if 语句都会触发。
  • @VLAZ 很抱歉造成混乱。 state.selectedItem 随着选择轮位置的变化而变化。我在帖子中留下了一些我认为不相关的功能,而且一定是漏掉了!我已将该代码添加到帖子中。谢谢!

标签: javascript reactjs react-native setstate


【解决方案1】:

我没有看太多你的代码,因为你已经正确更新了一些东西......如果你有一个逻辑错误,你会发现它。

也许您的问题可能是 setState 是在后台异步执行的。还有一个批处理系统。

过去我需要同步 setState 来进行逻辑控制。我使用同步回调来做这些事情......

this.setState({ key: value }, function() {
    // Do Something Here After State is Updated
    yourFunction();
});

在此处查看有关同步 setState 回调的更多信息:When to use React setState callback

祝你好运!

【讨论】:

    猜你喜欢
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    • 2011-07-13
    • 2021-10-20
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多