【问题标题】:setting the state at the beginning在开始时设置状态
【发布时间】:2020-02-25 05:29:03
【问题描述】:

函数每10秒返回一个随机字符串,我想在函数开头的字符串数组中设置一个单词

我尝试在生命周期开始时设置状态

  componentDidMount(){
    this.setState({
        randomItem: 
  this.setState({randomItem:this.randomItemGenerator()})
    },
    this.interval = setInterval(() => {
        this.setState({randomItem:this.randomItemGenerator()})
    }, 10000)
  });

-组件

class Word extends Component {
state={
    randomItem:''
}

myArray = [
    "esplendor",
    "diciendo",
    "impredecible",
    "problema",
    "terreno",
    "instante",
];

randomItemGenerator = () => (
    this.myArray[Math.floor(Math.random()*this.myArray.length)]
)

componentDidMount(){
    this.setState({
        randomItem: this.setState({randomItem:this.randomItemGenerator()})
    },
    this.interval = setInterval(() => {
        this.setState({randomItem:this.randomItemGenerator()})
    }, 10000)
});




render(){
   return(
      <div><h3>{this.state.randomItem}</h3></div>
   )
}
}

在componentdidmount之前还有另一个生命周期吗?

【问题讨论】:

    标签: javascript arrays reactjs setstate


    【解决方案1】:

    由于myArrayrandomItemGenerator不使用props或其他状态,你可以移动组件的外部,在初始化状态时使用它们。

    const myArray = [
      "esplendor",
      "diciendo",
      "impredecible",
      "problema",
      "terreno",
      "instante",
    ]
    
    const randomItemGenerator = () => (
      myArray[Math.floor(Math.random() * myArray.length)]
    )
    
    class Word extends React.Component {
      state = {
        randomItem: randomItemGenerator()
      }
    
      componentDidMount() {
        this.interval = setInterval(() => {
          this.setState({
            randomItem: randomItemGenerator()
          })
        }, 10000)
      }
      
      componentWillUnmount() { // clear the interval when the component is unmounted
        clearInterval(this.interval);
      }
    
      render() {
        return (
          <div><h3>{this.state.randomItem}</h3></div>
        )
      }
    }
    
    ReactDOM.render(
       <Word />,
      root
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    
    <div id="root"></div>

    但是,您可能希望从 props 中获取单词数组。在这种情况下,将randomItemGenerator 更改为接受数组作为参数,并在调用函数时传递相关属性(示例中为words)。

    const randomItemGenerator = (words) => (
      words[Math.floor(Math.random() * myArray.length)]
    )
    
    class Word extends React.Component {
      state = {
        randomItem: randomItemGenerator(this.props.words)
      }
    
      componentDidMount() {
        this.interval = setInterval(() => {
          this.setState({
            randomItem: randomItemGenerator(this.props.words)
          })
        }, 10000)
      }
      
      componentWillUnmount() { // clear the interval when the component is unmounted
        clearInterval(this.interval);
      }
    
      render() {
        return (
          <div><h3>{this.state.randomItem}</h3></div>
        )
      }
    }
    
    const myArray = [
      "esplendor",
      "diciendo",
      "impredecible",
      "problema",
      "terreno",
      "instante",
    ]
    
    ReactDOM.render(
       <Word words={myArray} />,
      root
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    
    <div id="root"></div>

    【讨论】:

      【解决方案2】:

      只需在状态初始化中调用你的函数:

      class Word extends Component {
          state = {
              randomItem: this.randomItemGenerator()
          }
      

      【讨论】:

      • TypeError: this.randomItemGenerator 不是函数,我将函数移到 state 之前,但它显示 TypeError: Cannot read property 'minutes' of null
      • 我在您的代码中看不到任何分钟属性访问权限。您会与更新后的代码共享一个 codepen 吗?
      猜你喜欢
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 2019-08-24
      • 2020-11-02
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      相关资源
      最近更新 更多