完整demo https://gitee.com/siyuev5/react-demo/tree/master/react-redux-demo
react-redux 是为了让react更好的使用redux开发的,下面看看使用方法。
首先安装好包 npm install redux react-redux
src下面创建 store目录,然后store 下面创建几个文件
/store/index.js
import { createStore } from 'redux'
import reducer from './reducer'
const state = createStore(reducer)
export default state
/store/reducer.js
const defaultState = {
list: [],
inputValue: ''
}
export default (state = defaultState, action) => {
switch (action.type) {
case 'change_input_value': {
return {
...state,
inputValue: action.value
}
}
case 'add_list_item': {
return {
...state,
list: [...state.list, state.inputValue],
inputValue: ''
}
}
default:
break
}
return state
}
然后创建 src/TodoList.jsx
import React, { Component } from 'react'
import { connect } from 'react-redux'
class TodoList extends Component {
render() {
return (
<React.Fragment>
<input
onChange={this.props.changeInputValue}
value={this.props.inputValue}
/>
<input onClick={this.props.addListItem} type="button" value="提交" />
<ul>
{this.props.list.map((value, index) => {
return (
<li key={index} index={index}>
{value}
</li>
)
})}
</ul>
</React.Fragment>
)
}
}
const mapStateToProps = state => {
return {
inputValue: state.inputValue,
list: state.list
}
}
const mapDispatchProps = dispatch => {
return {
changeInputValue(e) {
const action = {
type: 'change_input_value',
value: e.target.value
}
dispatch(action)
},
addListItem() {
const action = {
type: 'add_list_item'
}
dispatch(action)
}
}
}
export default connect(
mapStateToProps,
mapDispatchProps
)(TodoList)
src/index.js 入口文件
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import store from './store'
import TodoList from './TodoList'
const App = (
<Provider store={store}>
<TodoList />
</Provider>
)
ReactDOM.render(App, document.getElementById('root'))
首先来看 index.js 文件
react-redux
提供了一个 Provider
组件,在该组件的属性 store
连接到 redux 这样容器组件就能拿到 state 了。
再看看 src/TodoList.jsx
react-redux
提供了一个 connect
方法,该方法可以把 UI组件生成为容器组件并且连接起来
方法的第一个参数如下, 就是一个函数,这个函数的第一个参数 就是 redux 的 state,返回的对象就是你要挂载到当前组件 props
的内容
const mapStateToProps = state => {
return {
inputValue: state.inputValue,
list: state.list
}
}
connect
方法第二个参数也是一个函数如下,第一个参数就是 redux 的 dispatch
,这个函数返回一个对象同样挂载到 当前组件的 props
中。
const mapDispatchProps = dispatch => {
return {
changeInputValue(e) {
const action = {
type: 'change_input_value',
value: e.target.value
}
dispatch(action)
},
addListItem() {
const action = {
type: 'add_list_item'
}
dispatch(action)
}
}
}