繁体   English   中英

如何使用 componentWillRecieveProps 在 React Native 中重新渲染 Flatlist?

[英]How to re-render Flatlist in React Native using componentWillRecieveProps?

    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() 重新渲染新数据?

你应该使用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};
}

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

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

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

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

然后在你的render

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

   // then use map(employees) 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM