【问题标题】:Why does only one of the two objects from array get passed as prop?为什么数组中的两个对象中只有一个作为道具传递?
【发布时间】:2018-02-15 04:22:11
【问题描述】:

Im 试图将 prop 传递给另一个组件。数据(事件)来自 fetch 调用。我确实得到了道具,但不是我期望的那样。 当我控制台登录 willMount 时,我只能获得第一个对象,而当我控制台登录渲染功能时,我确实收到了两个对象。理想情况下,我想在 willMount 函数中获取这两个对象。任何人都可以解释为什么会发生这种情况,以及他们是否是一种让他们都控制台登录 willMount 的方法? Thank 你.

//PARENT
whoHasGame = (event) => {
        if(event.error){
            return;
        }else{
            console.log("event in MV", event)//console logs correctly
            this.setState({
                leagueInfo: <LeagueCard event={event}/>
            })
        }
    }

    render(){
        return (
            <ScrollView>
                {this.state.leagueInfo}
            </ScrollView>    
            );
    }

  //CHILD
  export default class LeagueCard extends Component {
  constructor(props) {
    super(props);
    this.state = {}
  }


  componentWillMount() { 
    console.log(this.props.event) //only the first object makes it
  };



  render() {
    //console.log(this.props.event)<-- but here both objects make it

    return (
      <View>
        <CardSection>
          <Text>League Name Goes Here</Text>
        {/* <TouchableOpacity onPress={this.display}>
          <Card>
            <CardSection>
              {this.state.matches}
            </CardSection>
          </Card>
        </TouchableOpacity> */}
        </CardSection>
      </View>
    )
  }
}

【问题讨论】:

  • componentWillMount 还是 componentDidMount ?在阙。你说didMount。另外请分享whoHasGame 如何与dom联系
  • @RIYAJKHAN 它会安装我的道歉。我还截屏了 whoHasGame 的调用方式。
  • 两个对象都没有在一次渲染中获得控制台。它们正在从您的共享输出中逐一渲染。请纠正我。componentWillMount 在生命周期中仅调用一次。render 为每次更新调用
  • @RIYAJKHAN 这是正确的。这似乎是我的问题。

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


【解决方案1】:

根据当前的实现:

this.setState({
                leagueInfo: <LeagueCard event={event}/>
            })

第一次调用whoHasGame时,调用setState。它使用第一个对象安装组件LeagueCard

由于componentWillMount 在生命周期中仅被调用一次,它会打印该对象。它还会在render 中对其进行控制台。

现在,再次调用 whoHasGame 时,由于调用了 setState,它会使用第二个对象重新渲染

这一次,componentWillMount 没有被调用,但render 再次被调用并控制第二个对象。

它将持续到第 n 个对象。

要在组件第一次渲染时获取所有对象,您需要调用一次setState

在您的情况下,setState 被称为 nth 时间基于对象计数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多