在React Js中动态渲染数组元素

时间:2020-01-09 17:20:50

标签: javascript arrays reactjs

我正在开发一个React JS应用程序。我想根据标题+日期在一系列字母中选择一个字母。然后,所选字母应显示在下方。这就是我所做的:

class ReceivedLetters extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedLetterIndex: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  componentDidMount() {
    if (this.props.receivedLetters[0]) {
      this.setState({
        selectedLetterIndex: 0
      });
    }
  }

  handleChange(e) {
    this.setState({ selectedLetterIndex: e.target.value });
  }

  getListOfLetters = () => {
    var list = [];
    for (let i = 0; i < this.props.receivedLetters.length; i++) {
      list.push(
        <option value={i}>
          {this.props.receivedLetters[i].mailingDate}
          {this.props.receivedLetters[i].title} {i}
        </option>
      );
    }
    return list;
  };

  render() {
    return (
      <div className="containerReceivedLetters">
        <div class="form-group">
          <label for="sel1">Select the letter:</label>
          <select onChange={this.handleChange} class="form-control" id="sel1">
            {this.getListOfLetters()}
          </select>
        </div>
        <div>
          my index is = {this.state.selectedLetterIndex} {/*THIS IS WORKING FINE,I CAN SELECT A LETTER AND RENDER ITS INDEX */}
          <br />
          {this.props.receivedLetters[0].letterBody} {/* THIS WORKS (render bodyof letter 0)*/}
          {this.props.receivedLetters[this.state.selectedLetterIndex].letterBody } {/*SO WHY IS THIS NOT WORKING? */}
        </div>
      </div>
    );
  }
}

export default ReceivedLetters;

当我尝试呈现所选字母的正文时,出现此错误:

TypeError:无法读取未定义的属性“ letterBody”

有人可以帮助我了解问题所在吗?

3 个答案:

答案 0 :(得分:0)

我的猜测是,最初,在this.props.receivedLetters[0]真正具有价值之前,您的组件已经被渲染,因此您将获得this.props.receivedLetters[""].letterBody,这会引起警告。 “”是您的this.state.selectedLetterIndex的默认值。

答案 1 :(得分:0)

this.state.selectedLetterIndex最初应设置为0而不是""

答案 2 :(得分:0)

尝试使该状态值为空

{
  "name": "enterprises/some123/policies/policy1",
  "version": "11",
  "applications": [
    {
      "packageName": "com.google.samples.apps.iosched",
      "installType": "FORCE_INSTALLED"
    },
    {
      "packageName": "com.mycompany.myapp",
      "installType": "AVAILABLE"
    }
  ],
  "debuggingFeaturesAllowed": true
}