1. Create-react-app reactredux

2. CD.\reactredux\ (Enter project directory)

3.npm i react-redux npm i redux-thunk npm i redux-devtools-extension npm i axios

4. Project directory structure

Source code — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – :

App.js

import React from 'react'
import { Provider } from 'react-redux'
import store from './redux/store'
import WithList from './container/WithList'
function App() {
  return (
    <Provider store={store}>
      <WithList></WithList>
    </Provider>)}export default App

Copy the code

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>.document.getElementById('root'));Copy the code

constants.js

const GET_DATA = 'GET_DATA'
export { GET_DATA }
Copy the code

reducer.js

import { GET_DATA } from './constants'
let initState = {
  list: [],}function fn(state = initState, action) {
  switch (action.type) {
    case GET_DATA:
      return {
        ...state,
        list: action.data,
      }
    default:
      return state
  }
}
export default fn

Copy the code

action.js

import axios from 'axios'
import { GET_DATA } from './constants'

function getData(data) {
  return { type: GET_DATA, data }
}

function getDataAsync() {
  return async (dispatch) => {
    let res = await axios({
      method: 'GET'.url: 'http://127.0.0.1:5000/test',})// console.log(res)
    dispatch(getData(res.data))
  }
}

export { getDataAsync }

Copy the code

store.js

import { createStore, applyMiddleware } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk from 'redux-thunk'
import reducer from './reducer'

export default createStore(
  reducer,
  process.env.NODE_ENV === 'development'
    ? composeWithDevTools(applyMiddleware(thunk))
    : applyMiddleware(thunk)
)

Copy the code

List.jsx

import React from 'react'
export default function List(props) {
  console.log(props.list)
  return (
    <div>
      <button
        onClick={()= >{props. GetDataAsync ()}}> button</button>
      <ul>
        {props.list.map((item, index) => {
          return (
            <li key={index}>
              <h3>{item.name}</h3>
              <p>{item.age}</p>
              <p>{item.info}</p>
            </li>)})}</ul>
    </div>)}Copy the code

WhitList.jsx

import { connect } from 'react-redux'
import List from '.. /components/List'
import { getDataAsync } from '.. /redux/action'

export default connect(
  (state) = > ({
    list: state.list,
  }),
  { getDataAsync }
)(List)

Copy the code

Project interface file juejin.cn/post/698499…