【发布时间】:2026-01-28 14:00:01
【问题描述】:
所以,作为一个使用 redux 和 react-native 的初学者,我在这里遇到了一些棘手的情况。
当用户登录时,我想用用户数据更新 Redux 状态。我调用了一个登录方法,在那里我得到了一个网络令牌。紧接着我想用 redux-thunk 调度两个异步操作。问题是:
当这些动作被分派并且我得到来自 API 的响应时,我已经导航到另一个屏幕并且呈现列表的数据不处于 Redux 状态。
问题:我怎样才能“保持”程序直到我的状态更新,然后导航到下一页?
这是用户登录时发生的情况:
fetch("http://10.0.2.2:8000/api/api-token-auth/", {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.props.email,
password: this.props.password,
})
}).then((response) => response.json()
).then((jResponse) => {
console.log(jResponse);
this._onValueChange('token_id', jResponse.token);
this.props.loginUserSuccess();
this.props.navigation.navigate('MainMenue');
}).catch((error) => {
console.log(error);
this.props.loginUserFail();
})
}
在登录期间的某个地方,这两个动作应该被完全调度并且状态应该被更新:
export const profileLoad = () => {
return (dispatch) => {
AsyncStorage.getItem('token_id')
.then((token_id) => fetch("http://10.0.2.2:8000/api/profile/", {
method: "GET",
headers: {
'Authorization': 'JWT ' + token_id
}
})
.then((response) => response.json())
.then((answer) => {
dispatch({ type: PROFILE_LOAD, payload: answer});
})
.done());
}
}
export const productsLoad = () => {
return (dispatch) => {
AsyncStorage.getItem('token_id')
.then((token_id) => {
fetch("http://10.0.2.2:8000/api/profile/products/", {
method: "GET",
headers: {
'Authorization': 'JWT ' + token_id
}
}).then((anser) => anser.json())
.then((response)=> {
dispatch ({ type: PRODUCTS_LOAD, payload: response})
})
}
).done();
}
}
然后我想导航另一个屏幕并渲染一个列表(使用 ListView)以显示来自产品和配置文件的 JSON 数据。
--> 所以我终于想通了。 解决方案 1.) 如所述返回动作创建者的承诺 2.) 确保在 then 方法中放置一个回调函数
export const loadAllProfileData = ({navigate}) => {
return (dispatch) => {
dispatch(profileLoad())
.then(() => dispatch(productsLoad()))
.then(() => navigate('MainMenue'))
};
}
export const profileLoad = () => {
return (dispatch) => {
return AsyncStorage.getItem('token_id')
.then((token_id) => fetch("http://10.0.2.2:8000/api/profile/", {
method: "GET",
headers: {
'Authorization': 'JWT ' + token_id
}
})
).then((response) => response.json())
.then((answer) => {
dispatch({ type: PROFILE_LOAD, payload: answer});
})
}
}
export const productsLoad = () => {
return (dispatch) => {
return AsyncStorage.getItem('token_id')
.then((token_id) =>
fetch("http://10.0.2.2:8000/api/profile/products/", {
method: "GET",
headers: {
'Authorization': 'JWT ' + token_id
}
})
).then((answer) => answer.json())
.then((response)=> {
dispatch ({ type: PRODUCTS_LOAD, payload: response})
})
}
}
【问题讨论】:
标签: react-native redux