【问题标题】:React Native change state leads to mobx-state-tree exceptionReact Native 改变状态导致 mobx-state-tree 异常
【发布时间】:2021-11-21 10:29:36
【问题描述】:

我在更改我所在州的值时遇到问题。我有

state = {
    ......,
    tags: []
}

这些标签的填充方式如下:

tags: this.props.userStore.details.tags

标签是字典列表:

tags = [{'name': tag1, 'userSelect': true}, {'name': tag2, 'userSelect': false}]

我将它们全部显示在复选框中:

renderTagCheckbox() {
    return this.state.tags.map((item, key) => {
      return(
        <TouchableOpacity key={key} style={{flexDirection: "row", marginTop: 5, justifyContent: "center"}}>
          <CheckBox
            isChecked={item.userSelect}
            onClick={() => this.changeCheckboxValue(item)}
          />
          <Text>{item.name}</Text>
        </TouchableOpacity>
      )
    })
  }

在我的changCheckboxValue() 我有:

  changeCheckboxValue(item) {
    //this.refersSubscriptions.forEach(s => s.remove())
    let currentTags = this.state.tags
    currentTags.forEach(tag => {
      if (tag===item) {
        tag.userSelect = !tag.userSelect
      }
    })
  }

这样我想我可以用currentTags setState 来改变值,但我得到一个错误:

[mobx-state-tree]Cannot modify 'tags@/userStore/details/tags/0', the object is protected and can only be modified by using an action.

有人能告诉我我做错了什么吗?

【问题讨论】:

  • 你能分享产生错误的代码sn-p吗?
  • @novonimo 问题出在changeCheckboxValue - 当我尝试tag.userSelect = !tag.userSelect 时出现错误
  • 您是否使用“useState”挂钩来创建您的状态?你用的是类组件还是函数组件?
  • @novonimo 我正在使用没有 useState 的类组件
  • 您的标签是否存储在全局存储中?

标签: react-native setstate mobx-state-tree


【解决方案1】:

来自mobx-state-tree 文档:

默认情况下,节点只能通过其中一项操作或树中更高级别的操作来修改。

您将tags 置于一个不可变对象的全局状态。因此,请避免通过组件中的内联代码更改全局状态。

您可以定义 propper actions 并为这些更改分派它们。

有关mobx-state-tree 中操作的更多信息,请查看documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 2019-11-26
    相关资源
    最近更新 更多