Javascript 在componentDidMount中设置从操作接收的状态数据
我在componentDidMount中调用一个操作,如下所示Javascript 在componentDidMount中设置从操作接收的状态数据,javascript,reactjs,react-redux,Javascript,Reactjs,React Redux,我在componentDidMount中调用一个操作,如下所示 componentDidMount() { const { allowedEvcCards} = this.props; allowedEvcCards(id); } 通过这些操作,我正在进行API调用并接收一些数据作为响应。我已将数据设置为带有减速器的状态。我想在componentDidMount中执行一些逻辑,并使用响应中接收到的数据自行安装 例如,在我的减速机中,我正在这样做 case ALLOWED_E
componentDidMount() {
const { allowedEvcCards} = this.props;
allowedEvcCards(id);
}
通过这些操作,我正在进行API调用并接收一些数据作为响应。我已将数据设置为带有减速器的状态。我想在componentDidMount中执行一些逻辑,并使用响应中接收到的数据自行安装
例如,在我的减速机中,我正在这样做
case ALLOWED_EVC_SUCCESS:
return {
...state,
allowedEvc: action.data
}
在componentDidMount
中,我想使用allowedEvc
。但它返回未定义,因为此时操作调用尚未完成
我的行动
// Get allowed Evc cards
export const ALLOWED_EVC_LOADING = 'ALLOWED_EVC_LOADING';
export const ALLOWED_EVC_SUCCESS = 'ALLOWED_EVC_SUCCESS';
export function allowedEvcCardsLoading() {
return {
type: ALLOWED_EVC_LOADING
}
}
export function allowedEvcCardsSuccess(data) {
return {
type: ALLOWED_EVC_SUCCESS,
data
}
}
export function allowedEvcCards(id) {
return dispatch => {
dispatch(allowedEvcCardsLoading());
axios.get(`${API_URL}/****/****/${id}/*****`, {
headers: {
// 'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
})
.then(res => {
console.log("Allowed EVC response ", res.data);
if (res.data.success === true) {
dispatch(allowedEvcCardsSuccess(res.data));
} else {
console.log("error");
// alert("error");
}
})
}
}
不幸的是,
componentDidMount
仅在安装组件时调用。除非您卸载它,否则无法使用该属性。但是,您可以使用componentdiddupdate
,因为它一收到道具就会被调用
阅读更多关于这方面的内容
编辑:也许您可以尝试将axios承诺与数据一起返回并使用它
// Component
async componentDidMount() {
const { allowedEvcCards} = this.props;
const data = await allowedEvcCards(id);
// ... do something with data
}
// Action
export function allowedEvcCards(id) {
return dispatch => {
dispatch(allowedEvcCardsLoading());
return axios.get(`${API_URL}/****/****/${id}/*****`, {
headers: {
// 'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
})
.then(res => {
console.log("Allowed EVC response ", res.data);
if (res.data.success === true) {
dispatch(allowedEvcCardsSuccess(res.data));
return res.data;
} else {
console.log("error");
// alert("error");
}
})
}
}
您可以使用connect访问减速机值吗?我正在使用connect。但是我的状态返回undefined,因为操作未完成yetCan我知道您正在使用哪个中间件吗?api调用是在哪里编写的?中间件是redux thunk。使用axios进行API调用。@PrakashT我已在问题
返回res.data中包含了我的操作代码>?是返回数据,以便将其分配给组件中的数据。OP正在使用reduxYes,不管怎样,它都可能返回一个值