将React组件推入React状态数组

时间:2019-02-21 11:19:05

标签: javascript reactjs

我正在试验React: 我有2个数组(array1和array2)包含一些单词。 我想通过循环2个数组(array1和array2)并在每次迭代时将组件“ Sentence”推入状态数组来初始化名为“句子”的React状态数组。这是我的代码:

import React, { Component } from "react";
import "./App.css";
import Sentence from "./Sentence.js";

var array1 = ["hello", "some", "words", "house", "garden", "car"];
var array2 = ["other", "bag", "of", "words", "oh", "yeah"];

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sentences: []
    };
  }

  componentDidMount() {
    for (var i = 0; i < array1.length; i++) {
      for (var j = 0; j < array2.length; j++) {
        let newArray = this.state.sentences.slice();
        newArray.push( <Sentence word1={array1[i]} word2={array2[j]} /> );
        this.setState({ sentences: newArray });
      }
    }
  }

  render() {
    return (
      <div>
        {this.state.sentences[0]}
        {this.state.sentences[1]}
        {this.state.sentences[2]}
      </div>
    );
  }
}

export default App;

这是Sentence.js:

import React, { Component } from "react";

class Sentence extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      word1: this.props.word1,
      word2: this.props.word2
    };
  }

  render() {
    return (
      <div>
        First word: {this.state.word1}
        <br />
        Second word: {this.state.word2}
      </div>
    );
  }
}
export default Sentence;

但是,在浏览器中,我只会看到:

First word: car
Second word: yeah

我期望的结果是看到状态数组的前3个部分(句子)的第一个和第二个单词。

1 个答案:

答案 0 :(得分:1)

setState是异步的。 this.state.sentence不会在循环内更新。

要么先构建阵列,然后一次将其全部推入。

let sentences = this.state.sentences.slice();

for (var i = 0; i < array1.length; i++) {
  for (var j = 0; j < array2.length; j++) {
    sentences.push( <Sentence word1={array1[i]} word2={array2[j]} /> );
  }
}

this.setState({ sentences: sentences });

或使用setState的回调版本

for (let i = 0; i < array1.length; i++) {
  for (let j = 0; j < array2.length; j++) {
    this.setState((state) => {
      return {
        sentences: [
          ...state.sentences, 
          <Sentence word1={array1[i]} word2={array2[j]} />
        ]
      }
    });
  }
}

此外,您的句子组件不需要状态:

const Sentence = ({ word1, word2 }) => (
  <div>
    First word: {word1}
    <br />
    Second word: {word2}
  </div>
);
export default Sentence;

我会这样构建

var array1 = ["hello", "some", "words", "house", "garden", "car"];
var array2 = ["other", "bag", "of", "words", "oh", "yeah"];

class App extends Component {
  constructor(props){
    super(props);

    this.state = { pairs: [] };
    for(const word1 of array1) {
      for(const word2 of array2) {
        this.state.pairs.push({ word1, word2 });
      }
    }
  }

  render() {
    return (
      <div>{
        this.state.pairs.map(words => <Sentence ...words />)
      }</div>
    );
  }
}