src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList'
import {Provider} from 'react-redux'
import store from './store'
// Provider可以包裹多个组件,这些组件都可以去store(Provider的属性store)直接拿state的值
//注意是Provider包裹过的组件全部包裹以后声明一个变量,挂载渲染的时候传这个变量就可以
const App=(
<Provider store ={store}>
<TodoList />
</Provider>
)
ReactDOM.render(App,document.getElementById('root'))
src/store/index.js
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store
src/TodoList.js
import React, { Component } from 'react';
// import store from './store'
import {connect} from 'react-redux'
import { ONCHANGE,UPLOAD } from './constants.js'
//使用了connect以后注释掉的方式就可以不用了
class TodoList extends Component {
constructor(props) {
super(props);
// this.state=store.getState()
}
render() {
return ( <div>
<div>
{/* <input value={this.state.inputValue}/> */}
<input value={this.props.inputValue} onChange={this.props.onChange}/>
<button onClick={this.props.onClick}>提交</button>
</div>
<ul>
{
this.props.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 {
onChange(e){
let action ={
type:ONCHANGE,
value:e.target.value
}
dispatch(action)
},
onClick(){
let action ={
type:UPLOAD,
}
dispatch(action)
}
}
}
//connect两个参数都是传递影射关系
//第一个参数传递影射关系从state里拿到的值影射成属性
//第二个参数派发action行为影射成属性
export default connect(stateToProps,dispatchToProps)(TodoList);
src/store/reducer.js
import { ONCHANGE,UPLOAD } from '../constants.js'
const defaultState={
inputValue:'ddddda',
list:['kkkkk']
}
// diapatch过来action reducer修改state里面的值,返回新的state
export default (state = defaultState ,action)=>{
if (action.type === ONCHANGE){
let newState = JSON.parse(JSON.stringify(state))
newState.inputValue = action.value
return newState
}
if (action.type === UPLOAD){
let newState = JSON.parse(JSON.stringify(state))
newState.list.push(newState.inputValue)
newState.inputValue=''
return newState
}
return state
}
网友评论