![](/img/trans.png)
[英]Getting null values from state before fetching actual data from API call in React
[英]React loading screen before fetching API call
我是React和Redux的初學者,在我獲取第一個API調用以獲取一些信息以呈現應用程序所需呈現的信息之前(例如,如果用戶已登錄,其他一些數據),我沒有找到任何有關如何執行某種加載屏幕的示例。 )
我已經有React App使用Redux和React-Router了。 我需要在渲染HomePage之前創建一些加載屏幕。 該加載屏幕將一直處於活動狀態,直到我收到API的響應。 得到響應后,我會將其分派到存儲中並禁用加載屏幕。
我在這里找到了我需要它的示例: https : //boss.gg/ (他們也使用React)
將您的操作划分為不同的狀態:未決,成功,錯誤。 當您的請求待處理時,您的組件可以顯示一個加載屏幕,當請求完成或出現錯誤時,該屏幕將被替換。 借助redux-thunk,您可以創建asyc動作。
用某種偽代碼可以這樣工作:
您的actionType:
export const GET_EXAMPLE_ERROR = 'GET_EXAMPLE_ERROR':
export const GET_EXAMPLE_SUCCESS = 'GET_EXAMPLE_SUCCESS':
export const GET_EXAMPLE_PENDING = 'GET_EXAMPLE_PENDING':
您的動作:
export function getExampleSuccess(payload) {
return {
type: exampleActionTypes.GET_EXAMPLE_SUCCESS,
payload,
};
}
export function getExampleError(error) {
return {
type: exampleActionTypes.GET_EXAMPLE_ERROR,
error,
};
}
export function getExamplePending() {
return {
type: exampleActionTypes.GET_EXAMPLE_PENDING,
};
}
export function getExample() {
return async dispatch => {
dispatch(getExamplePending());
try {
const result = await exampleService.getData();
dispatch(getExampleSuccess(result));
} catch (error) {
dispatch(getExampleError(error));
}
};
}
您的減速器:
export default function exampleReducer(state = initialState.example, action) {
switch (action.type) {
case exampleActionTypes.GET_EXAMPLE_ERROR:
return {
...state,
example: {
...state.example,
error: action.error,
pending: false,
},
};
case exampleActionTypes.GET_EXAMPLE_SUCCESS:
return {
...state,
example: {
...state.example,
result: action.payload,
pending: false,
},
};
case exampleActionTypes.GET_EXAMPLE_PENDING:
return {
...state,
example: {
...state.example,
error: null,
pending: true,
},
};
default:
return state;
}
}
您的組件:
class ExampleComponent extends React.Component {
componentDidMount() {
this.props.getExample();
}
render() {
if( this.props.pending ) {
return <Loader />;
}
return <div>Your component</div>
}
}
const mapStateToProps => ({
pending: state.example.pending
});
const mapDispatchToProps => ({
getExample
})
export default connect(mapStateToProps, mapDispatchToProps)(ExampleComponent)
請注意,這是單個調用的示例。 您的待處理狀態可以是Redux存儲區不同部分中多個待處理狀態的組合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.