react-native页面间传递数据的几种方式

62次阅读

共计 1912 个字符,预计需要花费 5 分钟才能阅读完成。

1. 利用 react-native 事件 DeviceEventEmitter 监听广播
应用场景:
– 表单提交页面,A 页面跳转到 B 页面选人,然后返回 A 页面,需要将 B 页面选择的数据传回 A 页面。
– 多个多媒体来回切换播放,暂停后二次继续播放等问题。

代码如下:A 页面
componentDidMount() {
// 利用 DeviceEventEmitter 监听 concactAdd 事件
this.subscription = DeviceEventEmitter.addListener(‘concactAdd’, (dic) => {// dic 为触发事件回传回来的数据
// 接收到 update 页发送的通知,后进行的操作内容
if (dic.approver_list) {
this.setState((preState: Object) => {
this.updateInputValue(preState.approver_list.concat(dic.approver_list), ‘approver_list’);
return {approver_list: preState.approver_list.concat(dic.approver_list) };
});
}
if (dic.observer_list) {
this.setState((preState: Object) => {
this.updateInputValue(preState.observer_list.concat(dic.observer_list), ‘observer_list’);
return {observer_list: preState.observer_list.concat(dic.observer_list) };
});
}
});

componentWillUnmount() {
this.subscription.remove();
}

B 页面
// 触发 concactAdd 事件广播
handleOk = (names: []) => {
const {field} = this.props;
DeviceEventEmitter.emit(‘concactAdd’, { [field]: names });
}
2. 用 react-navigation 提供的路由之间
A 页面
// 定义路由跳转函数 cb 表示需要传递的回调函数
export const navigateToLinkman = (cb: Function, type?: string, mul?: boolean): NavigateAction =>
NavigationActions.navigate({routeName: ‘Linkman’, params: { cb, type, mul} });
// 跳转选择人员页面
handleSelectUser = () => {
Keyboard.dismiss();
this.props.actions.navigateToLinkman(this.selectedUser, ”, true);

// 选择人员后的回调函数
selectedUser = (selectUser: string[]) => {
this.setState((preState) => {
const newEmails = preState.emails.concat(selectUser);
const emails = […new Set(newEmails)];
return {
emails,
};
});
}
B 页面
handleToUser = () => {

navigation.state.params.cb(user.email, group);

}
3. 利用 react-navigation 提供的路由事件监听触发事件
在 A 页面路由失去焦点的时候触发该事件
componentDidMount() {
this.props.navigation.addListener(‘didBlur’, (payload) => {
if (this.modalView) this.modalView.close();
});
}
那么问题来了,为何不在页面卸载(componentWillunmount)的时候触发该事件?
如果不了解 react-native 和 react-navigation,会很困惑,A 页面卸载了,为什么还能接收到来自 B 页面的数据或者事件,原因是:react-navigation 中,A 页面跳转到 B 页面,A 页面没有卸载,只是在它提供的路由栈中堆积,例如 A 跳转到 B 中,A 页面不执行 componentWillunmount, 当每一个路由 pop 掉的时候才会执行 componentWillunmount, 卸载掉当前页面。

正文完
 0