在React with Meteor中使用componentWillMount无法读取未定义的属性

时间:2017-09-02 15:25:12

标签: javascript reactjs meteor

我无法弄清楚如何解决这个错误。我认为它与使用" bind"有关。因为这是ES6。我尝试将.bind(this)添加到构造函数的末尾。我也尝试过更换' componentWillMount'与' componentDidMount'。这是使用流星并做出反应。

错误:

未捕获的TypeError:无法读取属性'符号'未定义的     在Trades.render(Trades.jsx:9)

App.js

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

    this.state = { trades: [] };
  };

  componentWillMount() {
    this.setState({ trades: [
      {
        _id: 1,
        symbol: "GOOG",
        shares: 25,
      },
      {
        _id: 2,
        symbol: "WMT",
        shares: 50,
      },
    ]});
  }.bind(this)

  renderTrades() {
    return this.state.trades.map((trade) => (
      <Trades key={trade._id} trade={trade} />
    ));
  }

  render() {
    return(
      <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
          <div className="container">
              <div className="col s12 m4"><Trades />
              <h2>Trades</h2>
                <Divider/>
                  <List>
                    {this.renderTrades()}
                  </List>
                <Divider/>
            </div>
            </div>
          </div>
      </MuiThemeProvider>
    )
  }
}

Trades.js

  export default class Trades extends Component {
    render() {
      return (
        <ListItem
          primaryText={this.props.trade.symbol}
          leftAvatar={<Avatar src="img.jpg" />}
          />
      )
    }
  }

1 个答案:

答案 0 :(得分:1)

componentWillMountdocs)中使用setState并不是一个好主意,而是使用componentDidMount来检查Trades组件中的数组是否为空:

  componentDidMount() {
    this.setState({ trades: [
      {
        _id: 1,
        symbol: "GOOG",
        shares: 25,
      },
      {
        _id: 2,
        symbol: "WMT",
        shares: 50,
      },
    ]});
  }

 export default class Trades extends Component {
    render() {
      return (
        this.props.trade && this.props.trade.symbol? <ListItem
          primaryText={this.props.trade.symbol}
          leftAvatar={<Avatar src="img.jpg" />}
          /> : <div>loading...</div>

      )
    }
  }