在React/Redux应用中正确获取数据的方法有多种。下面是一种常见的做法:
const fetchData = () => {
return {
type: 'FETCH_DATA',
};
};
const initialState = {
data: null,
loading: false,
error: null,
};
const dataReducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_DATA':
return {
...state,
loading: true,
};
case 'FETCH_DATA_SUCCESS':
return {
...state,
loading: false,
data: action.payload,
};
case 'FETCH_DATA_ERROR':
return {
...state,
loading: false,
error: action.payload,
};
default:
return state;
}
};
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(dataReducer, applyMiddleware(thunk));
const fetchData = () => {
return (dispatch) => {
dispatch({ type: 'FETCH_DATA' });
fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => {
dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data });
})
.catch((error) => {
dispatch({ type: 'FETCH_DATA_ERROR', payload: error.message });
});
};
};
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: {data}</div>;
};
const mapStateToProps = (state) => {
return {
data: state.data,
loading: state.loading,
error: state.error,
};
};
export default connect(mapStateToProps, { fetchData })(MyComponent);
这样,当组件渲染时,会触发fetchData异步action来获取数据,并根据数据的状态显示不同的内容。
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅供参考,具体产品选择应根据实际需求进行评估和决策。
领取专属 10元无门槛券
手把手带您无忧上云