高全柱 發表於 2021-11-5 15:48:00

react-redux-toolkit学习

<p>react-redux负责状态管理,使用toolkit插件可以更方便,具体使用方式简单总结一下。<br>
toolkit官网</p>
<h2 id="安装redux">安装redux</h2>
<p>使用toolkit的需要配置react-redux一起使用。</p>
<pre><code class="language-shell">npm install react-redux@latest
npm install @reduxjs/toolkit
</code></pre>
<h2 id="使用toolkit的步骤">使用toolkit的步骤</h2>
<ol>
<li>配置一个reduxStore</li>
</ol>
<pre><code class="language-jsx">import { configureStore } from '@reduxjs/toolkit';
export const store = configureStore({
    reducer: {},
});
</code></pre>
<ol start="2">
<li>把store发布到react项目中</li>
</ol>
<pre><code class="language-jsx">import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';

ReactDOM.render(
    &lt;Provider store={store}&gt;
      &lt;App /&gt;
    &lt;/Provider&gt;,
    document.getElementById('root')
);
</code></pre>
<ol start="3">
<li>创建不定量的 redux state slice<br>
创建不同的slice.js</li>
</ol>
<pre><code class="language-jsx">import { createSlice } from '@reduxjs/toolkit';

const initialState = {
    value: 0,
};

export const counterSlice = createSlice({
    name: 'counter',
    initialState,
    reducers: {
      increment: (state) =&gt; {
            state.value += 1;
      },
      decrement: (state) =&gt; {
            state.value -= 1;
      },
      incrementByAmount: (state, action) =&gt; {
            state.value += action.payload;
      },
    },
});
//Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
</code></pre>
<ol start="4">
<li>把 slice reducers 添加到 store 中<br>
next, we need add slice to our store. By defining a field inside the reducer parameter, we tell the store to use this slice reducer function to handle all updates to that state.</li>
</ol>
<pre><code class="language-jsx">import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counter/counterSlice'
export const store = configureStore({
    reducer: {
      counter: counterReducer,
    },
});
</code></pre>
<ol start="5">
<li>在组件中使用state和actions</li>
</ol>
<pre><code class="language-jsx">import React from 'react';
import {useSelector, useDispatch} from 'react-redux';
import {increment, decrement} from './counterSlice';

export function Counter() {
    //从store中选择所需要的对应的 state
    const count = useSelector((state) =&gt; state.counter.value);
    const dispatch = useDispatch();

    return (
      &lt;div&gt;
            &lt;div&gt;
                &lt;button
                  aria-label="Increment value"
                  onClick={() =&gt; dispatch(increment())}
                &gt;
                  Increment
                &lt;/button&gt;
                &lt;span&gt;{count}&lt;/span&gt;
                &lt;button
                  aria-label="Decrement value"
                  onClick={() =&gt; dispatch(decrement())}
                &gt;
                  Decrement
                &lt;/button&gt;
            &lt;/div&gt;
      &lt;/div&gt;
    );
}
</code></pre>
<p><font color="red">总结:</font></p>
<ol>
<li>使用 toolkit 配置一个空状态管理仓库: <code>store</code></li>
<li>将刚配置的空的状态管理仓库配合 <code>react-redux</code>中的 <code>Provider</code> 使用到项目中,一般需要将 <code>Provider</code> 包裹在项目的最顶层父级元素外,这样可以保证这个<code>store</code>能够存储项目内的所有<code>state</code>.</li>
<li>使用toolkit中<code>createSlice</code>创建每个<code>state</code>对应的<code>actions</code>(一般一个状态的reducer放置在一个单独的文件中,便于管理和查看)</li>
<li>把第3步创建好的不定量个数的<code>reducer</code>配置到第1步创建的<code>store</code>中。</li>
<li>在项目中使用<code>react-redux</code>中提供的<code>useSelector</code>和<code>useDispatch</code>分别负责从<code>store</code>中获取对应的<code>state</code>以及触发改变<code>state</code>的动作函数<code>reducer</code>.</li>
</ol>
<p>注意:若state的动作函数是一个异步请求,则第3步中需要使用<code>createAsyncThunk</code>来创建<code>state</code>对应的<code>action</code>:</p>
<pre><code class="language-jsx">import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'

// First, create the thunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) =&gt; {
    const response = await userAPI.fetchById(userId)
    return response.data
}
)

// Then, handle actions in your reducers:
const usersSlice = createSlice({
name: 'users',
initialState: { entities: [], loading: 'idle' },
reducers: {
    // standard reducer logic, with auto-generated action types per reducer
},
extraReducers: (builder) =&gt; {
    // Add reducers for additional action types here, and handle loading state as needed
    builder.addCase(fetchUserById.fulfilled, (state, action) =&gt; {
      // Add user to the state array
      state.entities.push(action.payload)
    })
},
})

// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))
</code></pre><br><br>
来源:https://www.cnblogs.com/ymwmn/p/15513632.html
頁: [1]
查看完整版本: react-redux-toolkit学习