1. 安装
npm install --save react-redux
npm install --save redux
2.<Provider>提供器
在/src/index.js文件下添加<Provider>
import React from 'react';
import ReactDOM from 'react-dom';
import TidoList from './TidoList'
import { Provider } from 'react-redux'
import store from './store/index'
const App = (
<Provider store={store}>
<TidoList />
</Provider>
)
ReactDOM.render(
App,
document.getElementById('root')
);
3. connect连接器
import {connect} from 'react-redux' //引入连接器
export default connect(xxx,null)(组件名称);
新建测试例子TidoList.js文件,引入connect,它是一个连接器(其实它就是一个方法),有了这个连接器就可以很容易的获得数据了。
完整例子1:无状态组件
import React from 'react';
import { connect } from 'react-redux'
const TidoList = (props) => {
// 解构赋值
const { inputValue, inputChange, clickBtton, list } = props
return (
<div>
<div>
<input
value={inputValue}
onChange={inputChange}
/>
<button onClick={clickBtton}>提交</button>
</div>
<ul>
{list.map((item, index) => {
return (
<li key={index}>{item}</li>
)
})}
</ul>
</div>
);
}
const stateToprops = (state) => {
return {
inputValue: state.inputValue,
list: state.list
}
}
const disPatchToprops = (dispatch) => {
return {
inputChange(e) {
let action = {
type: 'change_input',
value: e.target.value
}
dispatch(action)
},
clickBtton() {
let action = {
type: 'change_List',
}
dispatch(action)
}
}
}
export default connect(stateToprops, disPatchToprops)(TidoList);
完整例子2:有状态组件
import React, { Component } from 'react';
import { connect } from 'react-redux'
class TidoList extends Component {
render() {
const {inputValue, inputChange, clickBtton, list } = this.props
return (
<div>
<div>
<input
value={inputValue}
onChange={inputChange}
/>
<button onClick={clickBtton}>提交</button>
</div>
<ul>
{list.map((item, index) => {
return (
<li key={index}>{item}</li>
)
})}
</ul>
</div>
);
}
}
const stateToprops = (state) => {
return {
inputValue: state.inputValue,
list: state.list
}
}
const disPatchToprops = (dispatch) => {
//进行action的派发和reducer对业务逻辑的编写
return {
inputChange(e) {
let action = {
type: 'change_input',
value: e.target.value
}
dispatch(action)
},
clickBtton() {
let action = {
type: 'change_List',
}
dispatch(action)
}
}
}
export default connect(stateToprops, disPatchToprops)(TidoList);
注释映射关系就是把原来的state映射成组件中的props属性,比如我们想映射inputValue就可以写成如下代码。
const stateToProps = (state)=>{
return {
inputValue : state.inputValue
}
}
stateToprops :这指映射中获取react-redux的数据
disPatchToprops:通过这个参数才能改变store中的值。
Reducer.js代码
const defaultState = {
inputValue: 'sansuihe',
list: []
}
var state = (state = defaultState, action) => {
if (action.type === 'change_input') {
const newState = JSON.parse(JSON.stringify(state))
newState.inputValue = action.value
return newState
}
if (action.type === 'change_List') {
const newState = JSON.parse(JSON.stringify(state))
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState
}
return state
}
export default state