使用redux和axios获取api数据

使用redux,我们可以轻松管理状态。因为如果您的组件需要共享和更新状态,那么就需要它。在本篇文章中,我将为您提供完整的redux设置,其中包括带有axios调用api获取数据的示例。

因此,让我们开始我们的redux教程。现在,通过在终端中运行以下代码来创建React项目:

npx create-react-app my-app

现在我们必须安装redux和react-redux。所以打开终端并一个接一个地运行两个命令。

npm install redux


//then


npm install react-redux


//then


npm install --save redux-thunk

在您的myapp\index.js文件,添加以下代码。

import {Provider} from 'react-redux';
import store from './store';


ReactDOM.render(
  <React.StrictMode>
  <Provider store={store}>
    <App />
  </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);

创建您的myapp\src\store\actions\userAction.js文件,添加以下代码。

export const UPDATE_USER = 'UPDATE_USER';


const fetch_user = (dispatch) => {
    axios.get('https://reqres.in/api/users')
    .then(res => res.json())
    .then(res => dispatch({type:UPDATE_USER,payload:res.data}))
}


export default fetch_user;

创建您的myapp\src\store\reducer\useruserReducer.js文件,添加以下代码。

import {UPDATE_USER} from '../actions/userAction';


const userReducer = (state = {},{type,payload}) => {
    // console.log(actions)
    switch (type) {
      case UPDATE_USER:
        return payload
      default:
        return state;
    }
}


export default userReducer;

创建您的mpapp\src\store\index.js文件,添加以下代码。

import {applyMiddleware, combineReducers, compose, createStore} from 'redux';
import userReducer from './reducers/userReducer';
import thunk from 'redux-thunk';


const allReducer = combineReducers({users:userReducer});


const InitialStates = {
  users: []
} 


const middleware  = [thunk];


const store = createStore(allReducer,InitialStates,compose(applyMiddleware(...middleware);


export default store;

我们准备在组件中使用redux。现在打开您的App.js文件,添加以下代码。

import fetch_user from './store/actions/userAction';
import { useSelector, useDispatch } from 'react-redux';


function App() {
  const users = useSelector(state => state.users);
  const dispatch = useDispatch();
  return (
    <div className="App">
      <h1>Redux Tutorial</h1>
      Users: <button onClick={()=>dispatch(fetch_user)}>Fetch Users</button>
      {
        users.length === 0 ? <p>No user found!</p> :
        users.map(user => <p key={user.id}>{user.first_name}</p>) 
      }
    </div>
  );
}
export default App;

这就是使用Axios Api调用的Redux完整指南示例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值