React学习总结part1:redux是什么、react-redux

it2026-08-17  8

redux 

作用:集中式管理react应用中多个组件共享的状态

精品参考文章

参考大神文章:Redux 入门教程(一):基本用法redux文档:Redux npm install --save redux

React 绑定库和开发者工具

npm install --save react-redux npm install --save-dev redux-devtools

 

redux和react没有任何关系redux是一个状态管理器redux相当于一个公共的容器来存放数据,哪个组件需要,就可以直接调用

 redux的三个核心API

store(相当于一个容器,用来保存数据的地方,整个项目中有且只能有一个 创建方式 Redux.createStore())action(相当于记录了各种方法,它是 store 数据的唯一来源。它是一个对象,有个type属性 写法:const action = {type:'ADD'},会通过store.dispatch() 将 action 传到 store)reducer(是一个函数,其实主要是操作action)(写法:function reducer(state=0,action){ })

store要知道这个reducer ,通过以下方法进行调用

写法:Redux.createStore(reducer)

具体用法:

index.js

subscribe:添加一个变化监听器。每当 dispatch action 的时候就会执行,state 树中的一部分可能已经变化。

import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import {createStore} from 'redux'; import {rootReducer} from './redux/reducers'; import App from './components/app'; import * as serviceWorker from './serviceWorker'; const store = createStore(rootReducer); //创建store const render=()=>{ ReactDOM.render( <App store={store}/>, document.getElementById('root') ); } //渲染 render(); // 监听state的变化 store.subscribe(render); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();

app.jsx

getState:它与 store 的最后一个 reducer 返回值相同

import React from 'react'; import * as actions from '../redux/actions'; export default class App extends React.Component{ // 添加 add=()=>{ const num = this.refs.numSelect.value*1; this.props.store.dispatch(actions.add(num)); } // 减少 del=()=>{ const num = this.refs.numSelect.value*1; this.props.store.dispatch(actions.del(num)); } render(){ return( <div> <p>展示count:{this.props.store.getState()}</p> <select ref="numSelect"> <option value='1'>1</option> <option value='2'>2</option> <option value='3'>3</option> </select> <button onClick={this.add}>增加+</button> <button onClick={this.del}>减少-</button> </div> ) } }

actions.js

import {ADD,DEL} from './actionType'; export const add = number => ({type:ADD,number}); export const del = number => ({type:DEL,number});

actionType.js

export const ADD="ADD"; export const DEL="DEL";

reducers.js

import {ADD,DEL} from './actionType'; export function rootReducer(state=0,action){ switch(action.type){ case ADD: return state+action.number; case DEL: return state-action.number; default: return state; } }

react-redux

安装命令: npm install react-redux

这是react的插件库,简化react中的redux

项目中引入Provider:

import {Provider} from 'react-redux';

UI组件:展示(负责展示层)容器组件:管理数据和业务逻辑(负责业务逻辑层)

API

Provider 让组件得到state数据connect UI组件生成容器组件

用法:

index.js

applyMiddleware:使用包含自定义功能的 middleware 来扩展 Redux 是一种推荐的方式。

Thunk :使用 Thunk Middleware 来做异步 Action

import React from 'react' import ReactDOM from 'react-dom'; import {createStore,applyMiddleware} from 'redux'; import {Provider} from 'react-redux'; import {rootReducer} from './redux/reducers'; // 我们自己创建的reducer import App from './container/app'; // import thunk from 'redux-thunk'; const store = createStore(rootReducer,applyMiddleware(thunk)); //创建store ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root'));

container/app

import React from 'react'; import {connect} from 'react-redux'; import Content from '../components/content.js'; import Home from '../components/Home.js'; import {add,del,addAsync} from '../redux/actions'; //要用仓库里的数据,需要通过connect把react组件和redux的store真正连接起来 // 多个组件 class APPIndex extends React.Component{ render(){ const {count,add,del,addAsync} = this.props; return( <div> <Content count={count} del={del}/> <Home count={count} add={add} addAsync={addAsync}/> </div> ) } } export default connect( state=>({count:state}), { add, del, addAsync } )(APPIndex)

Content.js

import React, {Component} from 'react'; export default class Content extends Component { state = { count: 0 } del = () => { this.props.del(); } render () { return ( <div> <span>{this.props.count}</span> <button onClick={this.del}>减少-</button> </div> ) } }

Home.js

import React, {Component} from 'react'; export default class counter extends Component { state = { count: 0 } add = () => { this.props.add(); } addAsync = () => { this.props.addAsync(); } render () { return ( <div> <span>{this.props.count}</span> <button onClick={this.add}>增加+</button> <button onClick={this.addAsync}>异步两秒之后+1</button> </div> ) } }

action.js

import {ADD,DEL} from './action-type.js'; export const add =()=>({type:ADD}) export const del =()=>({type:DEL}) //异步 export const addAsync =()=>{ return dispatch=>{ setTimeout(()=>{ dispatch(add()) },2000); } }

redux-thunk

这是react官方出品的middleware库,解决了在redux应用中实现异步的问题,返回的是一个函数

安装:npm install redux-thunk

import {createStore,applyMiddleware} from 'redux';import thunk from 'redux-thunk';const store = createStore(rootReducer,applyMiddleware(thunk)); //创建store //异步 export const addAsync =()=>{ return dispatch=>{ setTimeout(()=>{ dispatch(add()) },2000); } } //异步 export const addAsyn =(num=1)=>{ return (dispatch)=>{ dispatch({ type:STAT_DATA }); setTimeout(()=>{ dispatch({ type:ADD, num }); dispatch({ type:GET_DATA }); },2000); } } export function getRequest(){ return dispatch=>{ axios({ method: 'get', url:'' }) .then((res)=>{ const action={ type:'UPDATE', payload:{ reducer4:res.data.result[1].address } } return action; }) .catch((err)=>{ console.log(err) }) } }

 

 

最新回复(0)