官网demo https://github.com/reduxjs/redux/blob/master/examples/todos/src/index.js
目录结构
页面
/src/index.js
// /src/index.js
import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import App from './components/App'
import rootReducer from './reducers'
const store = createStore(rootReducer)
render(
/**
* Provider
* https://www.redux.org.cn/docs/react-redux/api.html
*/
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
<Provider store>
使组件层级中的 connect()
方法都能够获得 Redux store。
/src/components/App.js
// /src/components/App.js
import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList'
const App = () => (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
)
export default App
把上中下拆分成了三个组件,挨个查看
/src/containers/AddTodo.js
// /src/containers/AddTodo.js
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'
const AddTodo = ({ dispatch }) => {
let input
return (
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addTodo(input.value))
input.value = ''
}}>
<input ref={node => input = node} />
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}
export default connect()(AddTodo)
关于connect()(AddTodo)
函数将被调用两次。第一次是设置参数,第二次是组件与 Redux store 连接:connect(mapStateToProps,mapDispatchToProps, mergeProps)(MyComponent)
。
https://www.redux.org.cn/docs/react-redux/api.html
可以参考下边部分的Examples内容
/src/containers/VisibleTodoList.js
// /src/containers/VisibleTodoList.js
import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../components/TodoList'
import { VisibilityFilters } from '../actions'
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case VisibilityFilters.SHOW_ALL:
return todos
case VisibilityFilters.SHOW_COMPLETED:
return todos.filter(t => t.completed)
case VisibilityFilters.SHOW_ACTIVE:
return todos.filter(t => !t.completed)
default:
throw new Error('Unknown filter: ' + filter)
}
}
const mapStateToProps = state => ({
todos: getVisibleTodos(state.todos, state.visibilityFilter)
})
const mapDispatchToProps = dispatch => ({
toggleTodo: id => dispatch(toggleTodo(id))
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
任何时候,只要 Redux store 发生改变,mapStateToProps
函数就会被调用,该回调函数必须返回一个纯对象,然后再执行后边的(TodoList),这个对象会与组件的 props 合并。