# 准备

这里使用 json-server 模拟后端数据, json-server 是一个基于 JSON 的 HTTP 服务器,用于快速创建 RESTful API。

reducer 中,我们使用 redux-thunk 来处理异步操作, redux-thunk 是一个中间件,它允许我们返回一个函数而不是一个对象,并在函数中可以进行异步操作。

# 示例

  1. noteReducer 中,我们创建 initializenotescreateNoteAction 两个函数,分别用于初始化笔记列表和创建新的笔记。都是异步操作,所以使用了 redux-thunk 。调用时直接调用 dispatch 即可。
export const initializeNotes = () => {
  return async dispatch => {
    const notes = await noteServiece.getAll()
    dispatch(setNotes(notes))
  }
}
export const createNoteAction = (content) => {
  return async dispatch => {
    const newNote = await noteServiece.createNew(content)
    dispatch(createNote(newNote))
  }
}
  1. 而相对应的函数,在 noteServiece 中,我们使用 axios 来模拟后端数据,并返回相应的数据。
import axios from 'axios';
const baseUrl = 'http://localhost:3001/notes'
const getAll = async () => {
    const response = await axios.get(baseUrl)
    return response.data
}
const createNew = async (content) => {
    const object = { content, important: false}
    const response = await axios.post(baseUrl, object)
    return response.data
}
export default {
    getAll,
    createNew,
}
  1. App.js 中,我们使用 useEffect 来初始化笔记列表,并使用 useDispatch 来调用 initializeNotes 函数。
const App = () => {
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(initializeNotes())
  }, [dispatch])
  return (
    <div>
      <NewNote />
      <VisibilityFilter />
      <Notes />
    </div>
  )
}
  1. 我们把 store 商店注册提取到 index.js 中,简化 main.js

store.js

import { configureStore } from '@reduxjs/toolkit'
import noteReducer from './reducers/noteReducer'
import filterReducer from './reducers/filterReducer'
const store = configureStore({
  reducer: {
    notes: noteReducer,
    filter: filterReducer
  }
})
export default store

main.js

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