【问题标题】:How to re-render Flatlist in React Native using componentWillRecieveProps?如何使用 componentWillRecieveProps 在 React Native 中重新渲染 Flatlist?
【发布时间】:2020-02-03 06:43:07
【问题描述】:
    UNSAFE_componentWillMount(){
        this.props.EmployeeFetch();
    }

    renderRow(employee){
        return <ListItem employee={employee}/>;
    }
render(){
    return(
        <FlatList style={{flex:1,height:100}} 
        data = {this.props.employees}
        />
    );
    }
}
const mapStateToProps=state=>{
    const employees = _.map(state.employees,(val,uid)=>{
        return {...val,uid};
    });
    return {employees};
}
export default connect(mapStateToProps, {EmployeeFetch})(EmployeeList);

我在这里从 firebase 获取数据。起初它是空的,过了一段时间数据来了。那么,我将如何使用 Flatlist 和 componentWillRecieveProps() 重新渲染新数据?

【问题讨论】:

  • 您使用的是哪个数据库或实时数据库
  • 实时数据库
  • 也使用 react-redux 来管理状态。

标签: reactjs firebase react-native redux react-redux


【解决方案1】:

你应该使用2个返回函数。

1 哪个返回加载(活动指示器)

2 如果数据存在于任何状态,则返回数据。

    constructor(props) {
        super(props);
        this.state = { isLoading: true};
    }
  render() {
    if(this.state.isLoading){
          return( 
            <View> 
              <ActivityIndicator size="large" color="#0c9"/>
            </View>
    )}
    return(
        <FlatList style={{flex:1,height:100}} 
        data = {this.props.employees}
        />
    );

const mapStateToProps=state=>{
    const employees = _.map(state.employees,(val,uid)=>{
        return {...val,uid};
    });
    if(employees){
         this.state.isLoading = false;
    }

    return {employees};
}

注意:不要忘记导入 react 组件 如果您使用反应导航,请尝试使用导航事件来获取数据 api,而不是使用 UNSAFE_componentWillMount() 或找到其他解决方案。

【讨论】:

  • 我没有使用 state 而是 redux
【解决方案2】:

所以componentWillReceiveProps 已被弃用,您应该使用getDerivedStateFromProps

您可以在示例中这样使用它:

static getDerivedStateFromProps(props, state) {
   const { employees } = this.props;
   return employees;
}

然后在你的render:

render() {
   const { employees } = this.props;

   // then use map(employees) 
}

【讨论】:

  • 你能用我的代码详细说明一下吗?我是 RN 的新手
  • @BestOFBest 请用您的整个组件更新您的帖子,以便我可以看到道具等。
猜你喜欢
  • 1970-01-01
  • 2018-12-27
  • 2021-06-01
  • 1970-01-01
  • 2018-06-20
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 2018-06-26
相关资源
最近更新 更多