項目使用的主要框架:
- React-native 0.61.5
- React-redux 7.1.3
- React-navigation 4.2.2
- Dva 2.0.2
問題
RN項目中遇到了無限向下導航的場景,類似汽車之家論壇,帖子明細畫面點擊某個用戶的頭像,進入其動態畫面再點擊他的帖子,又進入帖子詳情畫面,再點擊其他用戶頭像,又進入他人動態畫面....
無限向下導航,即A-->B-->C-->B-->C-->B-->C...;每次畫面B或畫面C出現時,顯示的內容不同(根據ID從接口查詢數據),但畫面結構都是一樣的。
如果不集成Redux/Dva這種狀態管理,應該是沒問題的,因為狀態是和畫面實例綁定的,每次畫面B出現時,是不同的畫面實例。
如果集成了Redux/Dva狀態管理工具,則畫面B的所有實例狀態都被綁定在Redux中了,后一個畫面B的數據加載,會影響前一個畫面B的頁面顯示(返回的時候)!Model如下:
const defaultState = {
loading: true,
userId: null,
userInfo: null,
activites: [],
};
export default {
namespace: 'profile',
state: {...defaultState},
reducers: {
updateState(state, {payload}) {
let obj = {...state, ...payload};
return obj;
},
...
},
effects: {
*reset({payload = {}}, {call, put, select}) {
yield put(createAction('updateState')({...defaultState}));
},
...
},
};
解決方法
區分開每次畫面B加載時,保存在Redux中的狀態,上面profile的model中的狀態要改為
state: {
user0: {...defaultState},
user1: {...defaultState},
// ...
},
相當于畫面B在Redux中的state多了一個層級,sub state的key為“user” + ID,這樣每次畫面B出現時,就增加了一個sub state,這樣就不會影響前一個畫面B了。
另外,ID這個狀態值要維護在畫面B的實例里,畫面B的實例根據這個ID去Redux中查找對應的全部狀態。
@connect(({profile}) => ({...profile}))
class UserProfile extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
// 當前畫面實例的state key
stateKey:'user0',
};
}
componentDidMount() {
const {dispatch, navigation} = this.props;
let {user_id} = navigation.state.params;
let stateKey = "user" + user_id;
this.setState({stateKey});
// 之后每次action,都要帶上sub state key,否則不知道要更新哪個畫面的狀態
dispatch(createAction('profile/index')({forceRefresh: true, stateKey}));
}
}
export default UserProfile;
參考:
https://stackoverflow.com/questions/55211289/stack-same-screen-multiple-times-with-react-navigation
https://stackoverflow.com/questions/49865165/redux-nested-state-with-dynamic-key