什么是redux
redux 是一个独立的用于做状态管理的 JS 库(不是 react 插件库)
redux 可以用在react vue 中,但基本与 react 配合使用
redux 作用: 集中式管理react项目中多个组件共享的状态
redux的使用方式
## // 1、npm i redux -D
## // 2、新建 store --> index.js
import { legacy_createStore as createStore } from 'redux';
import reducer from "./reducer";
const store = createStore(
reducer,
// 下面这段代码是配合 redux-devtools 插件使用的,能更好的看 redux 的状态的改变
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
## // 3、新建 store --> reducer.js
// 下面是需要共享的状态数据
const defaultState = {
inputValue: 'write Something',
list:[
'vue',
'react',
'angle',
]
}
// 下面的这段注释是解决警告的(不用在意)
// eslint-disable-next-line
export default (state=defaultState,action) => {
// action 是 store.dispatch 传过来的
console.log(state, action)
// Reducer里只能接受state,不能改变state
// changeInput 是需要改变共享状态的组件传过来的值
if(action.type === 'changeInput') {
let newState = JSON.parse(JSON.stringify(state))
// action.value 是接收到的改变的值
newState.inputValue=action.value
return newState
}
return state;
}
## // 4、使用store里面的数据
// 这是一个类组件
import React, {Component} from "react";
import {Input,Button,List} from 'antd';
// 引入store
import store from "../store"
class Edit extends Component {
constructor(props) {
super(props)
// getStore 可以获取store里面的数据
this.state = store.getState()
this.changeInputValue = this.changeInputValue.bind(this)
this.storeChange = this.storeChange.bind(this)
store.subscribe(this.storeChange)
}
render() {
return (
<div>
<div>
<Input
placeholder={this.state.inputValue}
style={{width: '250px',marginRight: 10}}
onChange={this.changeInputValue}
/>
<Button type="primary">搜索</Button>
</div>
<div style={{margin:'10px',width:'300px'}}>
<List bordered dataSource={this.state.list} renderItem={item=>(<List.Item> {item}</List.Item>)}></List>
</div>
</div>
)
}
// 输入框监听值的变化的函数
changeInputValue(e) {
const action = {
type:'changeInput',
value: e.target.value
}
// 通过store.dispatch 将输入的值传到reducer里面
store.dispatch(action)
}
storeChange() {
this.setState(store.getState())
}
}
export default Edit;
// 完成以上步骤,就可以实现redux的简单使用了,在redux-devtools插件里就能看到redux里面的数据随着输入框输入的内容来变化了