RN - 页面跳转后刷新内容

ReactNative中使用Navigation页面跳转后刷新内容的常用方法。

引子

最近准备实习面试,把一些原理性的内容学习了一遍,对前端的认识又上升了一个层次。顺便把之前的项目重构了一遍,过去的代码真是不堪入目。正如第一次面试时面试官说的,“基础的东西弄明白了,找Bug也会快一点”。

之前做用户登录时遇到点小问题,登录成功后不刷新用户信息。逻辑如下:登录成功后获取到token,存入reduxlocalStorage,并且跳转到个人中心页面。个人中心页面在componentDidMount生命周期中请求后端获取用户信息并渲染。

当时以为是localStorage的缘故,因为ReactNative中的localStorage是异步的,于是用Promise封装了一下,模拟成了同步,问题依然没有解决。后来发现,原来是Navigation跳转页面后不会触发componentDidMount生命周期,所以才没有渲染内容。

Redux

比较靠谱的方法是使用React-Redux来管理状态,执行顺序是Connect (DATA AVAILABLE) -> constructor & componentWillMount & componentDidMount,即使在RN中没有componentDidMount也可以通过connect获取状态并更新。

所以可以将用户信息保存到redux,然后设置connect,通过props获取用户信息并触发渲染。或者只保存token,然后在componentWillReceiveProps生命周期中使用nextProps获取到token,再请求后端获取用户信息再渲染。

import {connect} from 'react-redux';

class My extends Component {
render() {
const {user} = this.props;
if (user) {
return (
<View title="用户信息" onPress={跳转编辑用户信息页面} />
);
} else {
return (
<View title="登录用户" onPress={跳转登录页面} />
);
}
}
}

const mapStateToProps = state => {
return {
token: state.user.token,
user: state.user.user,
};
};

export default connect(mapStateToProps)(My);

回调函数

如果不想使用Redux,也可以设置回调函数,然后在Navigation中通过参数传递回调函数并触发刷新,类似于子组件与父组件通过回调函数通信。

// A组件

export default class A extends Component {
refresh(state) {
this.setState({state: state})
}

render() {
return (
<Button
onPress={ () => {
this.props.navigation.navigate('B', {
refresh: () => { this.refresh() },
})
}}
/>
)
}
}
// B组件

export default class B extends Component {
this.props.navigation.state.params.refresh(state)
}
查看评论