react中redux的使用

2021-09-27 08:47:17 字數 1460 閱讀 3521

1.安裝redux

npm install redux 

2.store的建立   (src/store/index.js)

import from 'redux'

import reducer from './reducer'

const store = createstore(reducer)

(src/store/reducer.js) 管理store狀態的變化 

const defaultstate = {

inputvalue: ' ',

list: [ ] 

export default (state = defaultstate, action) => {

return state;

在需要的元件中引入store

import store from './store/index'

輸出store

store.getstate()

賦值給this.state

this.state = store.getstate()

修改輸入框資料。 

handleinputvalue(e) {

const action = {

type: 'change_input_value',

value: e.target.value

store.dispatch(action)

(src/store/reducer)     reducer不能修改state,必須深拷貝乙份之前的。

export default (state = defaultstate, action) => {

if(action.type === 'change_input_value') {

const newstate = json.parse(json.stringify(state))  

newstate.inputvalue = action.value;

return newstate;

return state;

頁面監聽資料

this.handlestorechange = this.handlestorechange.bind(this);

store.subscribe(this.handlestorechange);

handlestorechange() {

this.setstate(store.getstate())

react 中的redux的使用

在專案中安裝redux yarn add redux yarn add react redux 首先建立乙個store資料夾 在store資料夾中建立乙個index.js檔案 在index.js中建立乙個例項 import from redux const state createstore exp...

react中簡單使用redux

如果你一點不熟悉redux,看看這個 專案搭建好之後,安裝一下依賴,安裝一下redux 和 react redux 在src目錄下建乙個redux資料夾,在redux資料夾下建action資料夾和reducer資料夾,分別放我們的action和reducer 1,首先編寫我們的action。acti...

React使用Redux管理資料

redux 提供createstore這個函式,用來生成 store。createstore函式接受另乙個函式作為引數,返回新生成的 store 物件。中介軟體,用於非同步action import thunk from redux thunk 引入reducer import reducers f...