在React中正确使用redux-thunk的步骤如下:
npm install redux-thunk
// actions.js
import axios from 'axios';
export const fetchData = () => {
return (dispatch, getState) => {
dispatch({ type: 'FETCH_DATA_REQUEST' });
axios.get('https://api.example.com/data')
.then(response => {
dispatch({ type: 'FETCH_DATA_SUCCESS', payload: response.data });
})
.catch(error => {
dispatch({ type: 'FETCH_DATA_FAILURE', payload: error.message });
});
};
};
// reducer.js
const initialState = {
data: [],
loading: false,
error: null
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_DATA_REQUEST':
return { ...state, loading: true, error: null };
case 'FETCH_DATA_SUCCESS':
return { ...state, loading: false, data: action.payload };
case 'FETCH_DATA_FAILURE':
return { ...state, loading: false, error: action.payload };
default:
return state;
}
};
export default reducer;
// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
const store = createStore(reducer, applyMiddleware(thunk));
export default store;
// MyComponent.js
import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchData } from './actions';
const MyComponent = ({ data, loading, error, fetchData }) => {
useEffect(() => {
fetchData();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
};
const mapStateToProps = state => ({
data: state.data,
loading: state.loading,
error: state.error
});
const mapDispatchToProps = {
fetchData
};
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
这样,在React中就可以正确使用redux-thunk来处理异步操作了。当组件渲染时,会调用fetchData action,该action会发起异步请求并更新store中的state。组件可以通过props访问state中的数据,并根据数据的状态进行相应的渲染。
领取专属 10元无门槛券
手把手带您无忧上云