案例demo结构总截图
todoReducer是通过combineReducers()函数从store包下的reducer拆分出来,独立负责管理todo模块的数据
reducer.js:
import {combineReducers} from 'redux';
import {createStore} from 'redux'
import TodoReducer from '../page/todo/todoReducer'
const reducer= combineReducers({
todo: TodoReducer,
})
const store = createStore(reducer, + window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
export default store;
App.js:
import React, { Component } from 'react';
import {Provider} from 'react-redux';
import Todo from './page/todo/todo';
import store from './store/reducer'
class App extends Component{
render() {
return (
<div>
<Provider store={store}>
<Todo/>
</Provider>
</div>
)
}
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
action.js
export const buttonClickAction = () => ({
type: 'BUTTON_CLICK',
value: false
})
export const changeTextAction = () => ({
type: 'CHANGE_TEXT',
value: false
})
todo.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from './actions';
//定义组件
class Todo extends Component{
render() {
const {text, onChangeText, onButtonClick} = this.props;
return (
<div>
<h1 onClick={onChangeText}> {text} </h1>
<button onClick={onButtonClick}>click me</button>
</div>
);
}
}
const mapState = (state) => ({
text: state.todo.text
})
const mapDispatch =(dispatch) =>({
onButtonClick(){
dispatch(actions.buttonClickAction())
},
onChangeText(){
dispatch(actions.changeTextAction())
}
})
export default connect(mapState, mapDispatch)(Todo);
todoReducer.js
const initialState = {
text: 'Hello'
}
const TodoReducer = (state = initialState, action) => {
switch (action.type) {
case 'CHANGE_TEXT':
return {
text: state.text==='Hello' ? 'hello变为hi':'Hello'
}
case 'BUTTON_CLICK':
return {
text: state.text==='Hello' ? '按钮被点击':'Hello'
}
default:
return initialState;
}
}
export default TodoReducer