【问题标题】:Trying to setState using eval() function (React Native)尝试使用 eval() 函数设置状态(React Native)
【发布时间】:2019-06-21 11:45:59
【问题描述】:

我正在尝试将 for 循环中的多个状态设置为 false 或 true,具体取决于它们是否满足(if 语句)要求。 for 循环将遍历一个字符串数组,每个字符串代表一个状态。但我似乎无法在 this.setState 函数中使用 eval...

我尝试过在线研究,但没有一个解决方案符合我的问题或我想要解决的问题。我什至尝试了 eval(this.state.anything) = false 但它仍然不起作用并显示左手分配无效错误。

let businessState = [
      "this.state.groupName",
      "this.state.groupOwnerName",
      "this.state.groupDesc",
      "this.props.profile._id",
      "this.state.businessName",
      "this.state.businessDesc",
      "this.state.businessRegNo",
      "this.state.businessType",
      "this.state.businessEmail",
      "this.state.businessTel",
      "this.state.businessWeChat",
      "this.state.businessRegPhotoUri",
      "this.state.businessSignPhotoUri"
    ];

var temp = ""
for (i = 0; i < businessState.length; i++) {
  if (eval(businessState[i]) == ""){
    temp = businessState[i]+ "Error"

    this.setState({
      eval(temp): true
    })
  }
}

从上面的代码可以看出,我想对状态进行求值,如果这个特定状态持有的值是一个空字符串“”,我想设置这个状态名称+“错误”(例如,如果 this.state.email 为空字符串 "" 我想将 this.state.emailError 设置为 true。

【问题讨论】:

  • 这段代码有不止一个问题。您不能在作业的左侧使用eval 方法。这当然是错误的。 eval(temp) = 'something' 这是错误的。如果你想给temp 变量赋值,你必须像let temp = 'something' 这样使用它。第二个错误是在您的代码中使用 setState 是错误的。真正的用法是this.setState({temp : true});。只需摆脱 eval 并在构造函数中启动临时变量,例如 this.state = { temp: true }
  • 我明白了,但这不是我想要做的,temp 代表一个状态名称的字符串“this.state.exampleError”(字符串)我想使用 eval 的原因是指向实际状态(this.state.exampleError)并将其设置为 true。我已经尝试过你的方法,它只是将 temp 覆盖为 true,这不是我想要做的

标签: react-native eval


【解决方案1】:

试试this.setState({[temp]: true}),而不是this.setState({eval(temp): true})。方括号会将 temp 中存储的字符串值作为 setState 中的变量名输出。

This article gives a good explanation

This Stack Overflow question and the accepted answer also should help

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2019-06-27
    • 1970-01-01
    • 2020-09-24
    • 2021-08-15
    相关资源
    最近更新 更多