React Native array prop混淆

时间:2018-07-24 13:56:18

标签: javascript arrays reactjs react-native react-props

我有两个部分,父母(ManySpace)和孩子(OtherComponent)。 OtherComponentManySpace道具渲染两个具有两个不同数组的manyspace组件。

MANYSPACE1和MANYSPACE2渲染是完美的,但是由于我如何解决此问题而使第一个ManySpace和第二个ManySpace组件数组内容感到困惑。 希望我能解释我的问题

import React, { Component } from 'react'; //and other imports
  let MANYSPACE;
  let icerik;
  let firsttext;
  let firstinput;
  let answer1;
  let answerlength1;
  let secondtext;
  let secondinput;
class ManySpace extends Component {
  render() {
    MANYSPACE = this.props.manyspace;
    icerik = MANYSPACE[0].icerik;
    firsttext = MANYSPACE[0].firsttext;
    firstinput = MANYSPACE[0].firstinput;
    if (firstinput) {
      answer1 = MANYSPACE[0].firstinput.answer1;
      answerlength1 = answer1.length;
    }

    secondtext = MANYSPACE[0].secondtext;
    secondinput = MANYSPACE[0].secondinput;
    if (secondinput) {
      answer2 = MANYSPACE[0].secondinput.answer2;
      answerlength2 = answer2.length;
    }
  return (

  ) 
}

-我的其他组件

import React, { Component } from 'react'; //and other imports
  const MANYSPACE1 = [
    {
      icerik: 'lorem ipsum',
      firsttext: 'lorem ipsum',
      firstinput: {
        answer1: 'lorem ipsum'
      },
      secondtext: 'lorem ipsum'
    }
  ];
  const MANYSPACE2 = [
    {
      icerik:'lorem ipsum',
      firsttext: 'lorem ipsum',
      firstinput: {
        answer1: 'lorem ipsum'
      },
      secondtext: 'lorem ipsum',
      secondinput: {
        answer2: 'lorem ipsum'
      },
      thirdinput: {
        answer3: 'lorem ipsum'
      }
    }
  ];  
class OtherComponent extends Component {
    <ManySpace
      manyspace={MANYSPACE1}
    />
    <ManySpace
     manyspace={MANYSPACE2}
    />
}

1 个答案:

答案 0 :(得分:1)

render方法内创建变量,而不是为所有ManySpace实例共享一个变量。

示例

import React, { Component } from "react"; //and other imports

class ManySpace extends Component {
  render() {
    const MANYSPACE = this.props.manyspace;
    const { icerik, firsttext, firstinput } = MANYSPACE[0];
    let answer1, answerlength1;

    if (firstinput) {
      answer1 = MANYSPACE[0].firstinput.answer1;
      answerlength1 = answer1.length;
    }

    const { secondtext, secondinput } = MANYSPACE[0];
    let answer2, answerlength2;

    if (secondinput) {
      answer2 = MANYSPACE[0].secondinput.answer2;
      answerlength2 = answer2.length;
    }

    return (
      {/* ... */}
    );
  }
}