import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
//定义组件
class App extends Component{
render() {
const {text, onChangeText, onButtonClick} = this.props;
return (
<div>
<h1 onClick={onChangeText}> {text} </h1>
<button onClick={onButtonClick}>click me</button>
</div>
);
}
}
//action
const changeTextAction = {
type:'CHANGE_TEXT'
}
const buttonClickAction = {
type:'BUTTON_CLICK'
}
//reducer
const initialState = {
text: 'Hello'
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'CHANGE_TEXT':
return {
text: state.text=='Hello' ? 'world':'Hello'
}
case 'BUTTON_CLICK':
return {
text: 'Hello world'
}
default:
return initialState;
}
}
//store
let store = createStore(reducer);
//映射Redux state到组件的属性
function mapStateToProps(state) {
return { text: state.text }
}
//映射Redux actions到组件的属性
function mapDispatchToProps(dispatch){
return{
onButtonClick:()=>dispatch(buttonClickAction),
onChangeText:()=>dispatch(changeTextAction)
}
}
//连接组件
App = connect(mapStateToProps, mapDispatchToProps)(App)
//渲染组件
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
1.reducer框架:
const initialState = {
// 初始化state
}
let nameReducer = (state=initialState, action) => {
switch (action.type) {
case types.name:
return {
...state,
name: action.name,
}
}
}
Redux框架之createStore()用法讲解
createStore()
1.createStore(reducer, [initialState], enhancer)
2.创建一个store
3.应用中应有且仅有一个store
createStore() 的第二个参数是可选的, 用于设置 state 初始状态。这对开发同构应用时非常有用,服务器端 redux 应用的 state 结构可以与客户端保持一致, 那么客户端可以将从网络接收到的服务端 state 直接用于本地数据初始化
Reducer只进行一个传参的作用,永远不要进行,做其他复杂的操作
function todoApp(state = initialState, action) {
switch (action.type) {
case SET_VISIBILITY_FILTER:
return Object.assign({}, state, {
visibilityFilter: action.filter
})
default:
return state
}
}
1.不要修改state。使用Object.assign() 创建一个副本,不能这样使用Object.assign(stat...)
也可以使用es7中对象展开符号,{...state, ...newState} 这个代表全部列出来
default 情况一定要返回state
import { combineReducers } from 'redux'
const todoApp = combineReducers({
visibilityFilter,
todos
})
export default todoApp
完全等价 combineReducers这样就可以消灭一些
export default function todoApp(state = {}, action) {
return {
visibilityFilter: visibilityFilter(state.visibilityFilter, action),
todos: todos(state.todos, action)
}
}