在App启动时使用redux启动fetch,可以通过以下步骤实现:
下面是一个简单的示例代码:
// actions.js
export const fetchData = () => {
return async (dispatch) => {
try {
// 发起fetch请求,获取数据
const response = await fetch('https://example.com/api/data');
const data = await response.json();
// 将获取到的数据派发给Redux的reducer
dispatch({ type: 'FETCH_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', payload: error.message });
}
};
};
// reducer.js
const initialState = {
data: null,
error: null,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_SUCCESS':
return { ...state, data: action.payload };
case 'FETCH_ERROR':
return { ...state, error: action.payload };
default:
return state;
}
};
export default reducer;
// index.js
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducer';
import App from './App';
const store = createStore(reducer, applyMiddleware(thunk));
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
// App.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { fetchData } from './actions';
const App = () => {
const dispatch = useDispatch();
const data = useSelector((state) => state.data);
useEffect(() => {
dispatch(fetchData());
}, [dispatch]);
return (
<div>
{data ? (
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
'Loading...'
)}
</div>
);
};
export default App;
以上示例代码中,通过redux-thunk中间件支持异步Action的创建和dispatch,以及使用React Redux提供的useDispatch和useSelector钩子来在App组件中触发异步Action和获取Redux的状态。在示例中,使用了一个简单的fetch请求来获取数据,并将数据存储到Redux的状态中,然后在App组件中根据数据的状态进行渲染。
对应的腾讯云产品和产品介绍链接地址如下(仅供参考):
领取专属 10元无门槛券
手把手带您无忧上云