我正在使用列表视图
class GroupList extends Component {
componentWillMount() {
this.props.fetchGroups();
我从firebase获取了一个非常简短的元素列表。
export const fetchGroups = () => {
const { currentUser } = firebase.auth();
return (dispatch) => {
dispatch({
type: FETCHING_GROUPS
});
firebase.database().ref(`/users/${currentUser.uid}/groups`)
.on('value', snapshot => {
dispatch({
type: GROUPS_FETCHED,
payload: snapshot.val()
});
});
};
};
要创建一个新项目,我使用react-native-router-flux提供的右上角按钮
<Scene
key="groupList"
component={GroupList}
title="Gruppi di servizio"
hideNavBar={false}
rightTitle="Nuovo"
onRight={() => Actions.groupForm({ formType: NEW_GROUP_FORM_TYPE })}
sceneStyle={{ paddingTop: 65 }}
/>
所以我点击右上角的“新”按钮,我看到了我的表格。
然后用户保存新的组名
这是我保存到firebase的操作:
return (dispatch) => {
dispatch({
type: TRYING_TO_CREATE_GROUP,
});
firebase.database().ref(`/users/${currentUser.uid}/groups`)
.push({ groupName })
.then(() => {
dispatch({ type: CREATE_GROUP_SUCCESS });
Actions.groupList({ type: 'reset' });
})
.catch((errorText) => {
dispatch({
type: CREATE_GROUP_FAILED,
payload: errorText
});
});
};
有什么问题?
第一轮之后
Actions.groupForm({ formType: NEW_GROUP_FORM_TYPE })}
和
Actions.groupList({ type: 'reset' })
我的组列表已成功刷新,因为再次调用componentWillMount。
问题是在第二轮groupForm之后 - > groupList我的列表不再刷新。
将控制台日志添加到componentWillMount我发现它已不再执行了。
为什么?
什么是返回场景'groupList'的正确方法,不惜任何代价强制刷新?
我没有使用react-native-router-flux,但我遇到了同样的问题,希望能够给你足够的信息来弄清楚如何使用该库。
基本上它不再被调用(componentWillMount),因为组件已经被挂载并且它只是将焦点返回到该组件。您需要做的是将fetchGroups()
传递到下一个场景所在的位置,并在返回GroupList场景后再次调用它,这将导致使用最新信息重新渲染。如果我要进一步澄清,请告诉我。
我通过以下方式解决了这个问题
Actions.replace(sceneKey, props );
为了你的代码
Actions.replace('groupForm', { formType: NEW_GROUP_FORM_TYPE } );
希望这有帮助!
这对我有用。试试吧。它的要点是当你定义一个场景时,你可以覆盖它的“onBack”功能。为了强制刷新上一页,你必须每次为它提供一个具有不同值的prop,即Math.random()。
<Scene
key='title'
component={YourComponent}
title='Title'
onBack={() => Actions.pop({ refresh: Math.random() })}
/>
受@ Matt解决方案的启发,我解决了我的问题。我将发布我的示例代码。
这个想法是,如果你想从子页面路由回来时刷新父页面,我这样做的方法是将一个destroy和一个更新回调函数传递给子页面。 destroy函数确保页面回退到初始状态,而update函数将获取最新数据。
// parent scene
Actions.childSceneName({
onBack: () => this.props.fetchData(),
destroyParent: () => this.props.destroyPage(),
})
这样子页面可以在路由返回之前调用这些函数。
// child scene
componentWillUnmount() {
this.props.destroyParent()
this.props.onBack()
}