枚举React中的组件状态

时间:2018-04-23 11:31:54

标签: reactjs jsx

所以我想让一个组件迭代它的状态中的一个对象并将数据传递给它的孩子。我的父组件看起来基本上是这样的:

class ListContainer extends React.Component{
    constructor(props){
        super(props);

        this.state = {"stuff": {
            "pie": ["bread", "apple"],
            "fries": ["potatoes", "oil"]
            }
        };

    render(){
        let rendArr = [];
        for(recipe in this.state.stuff){
            let newRecipe = <Child tableName={recipe} recipeData={this.state.stuff[recipe]} />;
            rendArr.push(newRecipe);
        }

        return(
            <div id="11"> I work
                {rendArr}
            </div>
        );
    }

但是,我得到一个错误,说我在for循环中使用的“recipe”占位符未定义。我猜我在这里使用for循环错误的JSX,但我不知道迭代对象的正确方法。我知道我可能只是把它转换成一个对象或类似的数组,但是现在我想知道为什么这个for循环在React中不起作用。

3 个答案:

答案 0 :(得分:0)

不是在数组中推送组件,而是使用map方法推送对象并在渲染中拉出它:

var arr = [
  [1,2,3],
  [2,1,3],
  [2,3,1]
]

// Creates another array from arr organized by column
var byColumn = arr.reduce((accumulator, item) => {
  item.forEach((element, index) => {
    if(!accumulator[index]) accumulator[index] = [];
    accumulator[index].push(element);
  });
  return accumulator;
}, [])

// Gets the first array of arr to iterate
var firstArray = arr[0];

// Gets an array of elements that appears in all columns
var filteredNumbers = firstArray.filter(element => {
  return byColumn.every(item => item.includes(element));
});

console.log(filteredNumbers); // [1]

答案 1 :(得分:0)

使用render(){ let rendArr = []; for(recipe in this.state.stuff){ rendArr.push({tn: recipe, rd: this.state.stuff[recipe]}); } return( <div id="11"> I work { rendArr.map(el=> { <Child tableName={el.tn} recipeData={el.rd} /> }) } </div> ); } 代替for..in循环:

map

答案 2 :(得分:0)

ReactJS中:典型的做法是render lists使用Array.prototype.map()

Object.entries()Destructuring Assignment可以合并,以达到方便的形式。

请参阅下面的实例。

// List.
class List extends React.Component {

  // State.
  state = {
    recipes: {
      pie: ['bread', 'apple'],
      fries: ['potatoes', 'oil']
    }
  }

  // Render.
  render = () => (
    <div id="11">
    
      <h1>Map</h1>
      {this.map()}
      
      <h1>For Loop</h1>
      {this.forLoop()}
      
    </div>
  )
  
  // Map.
  map = () => Object.entries(this.state.recipes).map(([name, recipe]) => <Recipe key={name} name={name} recipe={recipe}/>)
  
  // For Loop.
  forLoop = () => {
    const list = []
    for (let name in this.state.recipes) {
      const recipe = this.state.recipes[name]
      const line = <Recipe key={name} name={name} recipe={recipe}/>
      list.push(line)
    }
    return list
  }
}

// Recipe.
const Recipe = ({name, recipe}) => (
  <div>
    <h3 style={{textTransform: 'capitalize'}}>{name}</h3>
    {recipe.map(ingredient => <div>{ingredient}</div>)}
  </div>
)

ReactDOM.render(<List/>, document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>