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兩個參數(shù)都是傳遞影射關(guān)系
//第一個參數(shù)傳遞影射關(guān)系從state里拿到的值影射成屬性
//第二個參數(shù)派發(fā)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
}