項(xiàng)目使用的主要框架:
- React-native 0.61.5
- React-redux 7.1.3
- React-navigation 4.2.2
- Dva 2.0.2
問題
RN項(xiàng)目中遇到了無限向下導(dǎo)航的場景,類似汽車之家論壇,帖子明細(xì)畫面點(diǎn)擊某個用戶的頭像,進(jìn)入其動態(tài)畫面再點(diǎn)擊他的帖子,又進(jìn)入帖子詳情畫面,再點(diǎn)擊其他用戶頭像,又進(jìn)入他人動態(tài)畫面....
無限向下導(dǎo)航,即A-->B-->C-->B-->C-->B-->C...;每次畫面B或畫面C出現(xiàn)時,顯示的內(nèi)容不同(根據(jù)ID從接口查詢數(shù)據(jù)),但畫面結(jié)構(gòu)都是一樣的。
如果不集成Redux/Dva這種狀態(tài)管理,應(yīng)該是沒問題的,因?yàn)闋顟B(tài)是和畫面實(shí)例綁定的,每次畫面B出現(xiàn)時,是不同的畫面實(shí)例。
如果集成了Redux/Dva狀態(tài)管理工具,則畫面B的所有實(shí)例狀態(tài)都被綁定在Redux中了,后一個畫面B的數(shù)據(jù)加載,會影響前一個畫面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}));
},
...
},
};
解決方法
區(qū)分開每次畫面B加載時,保存在Redux中的狀態(tài),上面profile的model中的狀態(tài)要改為
state: {
user0: {...defaultState},
user1: {...defaultState},
// ...
},
相當(dāng)于畫面B在Redux中的state多了一個層級,sub state的key為“user” + ID,這樣每次畫面B出現(xiàn)時,就增加了一個sub state,這樣就不會影響前一個畫面B了。
另外,ID這個狀態(tài)值要維護(hù)在畫面B的實(shí)例里,畫面B的實(shí)例根據(jù)這個ID去Redux中查找對應(yīng)的全部狀態(tài)。
@connect(({profile}) => ({...profile}))
class UserProfile extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
// 當(dāng)前畫面實(shí)例的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,否則不知道要更新哪個畫面的狀態(tài)
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