在反应中同时访问两个数组

时间:2018-10-25 12:24:37

标签: reactjs

我有下面提到的这部分代码,“ msg”和“ botMsg”是两个不同的对象数组。假设'msg'和'botMsg'的伪内容为:

let items = [
    {id: 3, parent: 5},
    {id: 5, parent: null},
    {id: 6, parent: 3},
    {id: 1, parent: null},
    {id: 4, parent: 7},
    {id: 2, parent: 1},
    {id: 7, parent: 2}
  ];
  let itemsNew = [];

  items = items.map(function(x){
    return {id: x.id, parent: x.parent, children: []};
  });

  // new array with parents only
  for(let i=items.length-1; i>=0; i--){
    if(items[i].parent == null){
      itemsNew.push(items[i]);
      items.splice(i, 1);
    }
  }

  for(let i=0; i<itemsNew.length; i++){
    let childIndexes = findChildAll(itemsNew[i].id);

    // sort the indexes so splicing the array wont misplace them
    childIndexes.sort(function(a,b){
      return b-a;
    });
    
    for(let j=0; j<childIndexes.length; j++){
      itemsNew[i].children.push(items[childIndexes[j]]);
      items.splice(childIndexes[j], 1);
    }
  }

  // returns an array of indexes of all the element's children and their children
  function findChildAll(parentId){
    for(let i=0; i<items.length; i++){
      if(items[i].parent == parentId){
        let resultArray = findChildAll(items[i].id);
        // is the result as an array add it to the index
        if(resultArray) return [i].concat(resultArray);
        // otherwise return just this index
        return [i];
      }
    }
  }
  
  console.log(itemsNew);

鉴于两个数组的长度相等,我如何在提到的第二个span标签中显示“ botMsg”内容。我想在每个“ msg”内容(我已在第一个span标签中显示)之后显示“ botMsg”内容。

 msg : [ {id: 1, content: 'hello' }, {id: 2, content: 'world'} ]
 botMsg : [{id: 3 content: 'yes'}, {id: 6, content: 'hii'} ]

}

所以我期望的输出是

const Msg = ({ msg, botMsg }) => { 

    const msgList = msg.length ? (
    msg.map((i,j) => {
        return(
            <span>
            <div key={i.id}>
                <span>{i.content}</span>
            </div>
            <div key={i.id}>
                <span>{}</span>
            </div>
            </span> 
        )
    })
) : (
    <p className="center">you have no msg yet</p>
)

1 个答案:

答案 0 :(得分:1)

赋予map(在代码示例中为j)的函数的第二个参数是当前元素的索引,因此您可以使用它来访问{{ 1}}数组。

示例

botMsg
class App extends React.Component {
  state = {
    msg: [{ id: 1, content: "hello" }, { id: 2, content: "world" }],
    botMsg: [{ id: 3, content: "yes" }, { id: 6, content: "hii" }]
  };

  render() {
    const { msg, botMsg } = this.state;

    return (
      <div>
        {msg.map((i, j) => {
          return (
            <span key={i.id}>
              <div>
                <span>{i.content}</span>
              </div>
              <div>
                <span>{botMsg[j].content}</span>
              </div>
            </span>
          );
        })}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));