【问题标题】:React can't pass state value to state arrayReact 无法将状态值传递给状态数组
【发布时间】:2019-07-13 09:08:17
【问题描述】:

在 React 中,我有一个名为 random 的状态属性,带有一个随机值。我正在尝试选择具有随机状态的 myArray2 值并将其传递到 myArray 状态中。

当我单击按钮时,警报方法应该显示其中一个随机数,但它似乎不起作用。

import React, { Component } from 'react';
import './App.css';



class App extends Component {

  //random = Math.floor(Math.random() * 3)

  constructor(props){
    super(props);

this.state = {
    random: Math.floor(Math.random() * 3),
    myArray2:['one','two','three'],
    myArray:this.state.myArray2[this.state.random]     
};

}

change = () => {
  alert(this.state.myArray);
}

  render() {
    return (
      <div className="App">
        <button onClick={this.change}>ok</button>
      </div> 

    );
  }


}

export default App;

这就是我得到的-

TypeError:无法读取未定义的属性“myArray2”

这就是我想要的-

显示随机数的警报方法

【问题讨论】:

  • 对于每个请求,您应该传递新的随机整数,在本例中,随机填充一次随机整数,并且不会因每个请求而更改
  • @Pleinair,集成解决方案运气好吗?

标签: reactjs


【解决方案1】:

这是目前基于类的组件无法做到的。但是,您可以让您的 change() 函数自行执行随机逻辑并有效地更新 random 和 myArray 状态。

this.setState() 有第二个回调参数,它使我们能够访问更新的状态。使用它来触发警报。

this.state = {
    random: Math.floor(Math.random() * 3),
    myArray2:['one','two','three'],
    myArray: null
};


  change = () => {
    const random = Math.floor(Math.random() * 3);
    this.setState(
      {
        random: random,
        myArray: this.state.myArray2[random]
      },
      () => alert(this.state.myArray) //now refers to the new state value
    );
  };

参考沙盒:https://codesandbox.io/s/confident-meadow-jumty

【讨论】:

    【解决方案2】:

    您的错误是在 state 中调用 state 并试图在没有 setState 的情况下更改 state 属性的值。 我想你应该想要这个

    import React, { Component } from "react";
    import ReactDOM from "react-dom";
    
    class App extends Component {
      state = {
        myArray2: ["one", "two", "three"],
        myArray: []
      };
    
      change = () => {
        let random = Math.floor(Math.random() * 3);
        this.setState({ myArray: this.state.myArray2[random] });
        alert(this.state.myArray);
      };
    
      render() {
        return (
          <div className="App">
            <button onClick={this.change}>ok</button>
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    

    【讨论】:

      猜你喜欢
      • 2019-09-18
      • 1970-01-01
      • 2019-03-08
      • 2019-01-20
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 2019-07-17
      相关资源
      最近更新 更多