React-Redux 的两个核心组件:
Provider提供器
connect连接器
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import ToDoList from './ToDoList'
import {Provider} from 'react-redux'
import store from './store'
const app=(
<Provider store={store}>
<ToDoList/>
</Provider>
)
ReactDOM.render(
app,
document.getElementById('root')
);
ToDoList.js
import React, { Component } from 'react';
import {connect} from 'react-redux'
import store from './store'
class ToDoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
}
render() {
return (
<div>
<input value={this.props.inputValue} onChange={this.props.inputChange}/>
<button onClick={this.props.addItem}>添加游戏</button>
{
this.props.list.map((value,key)=>{
return <li key={key} onClick={this.props.deleteItem}>{value}</li>
})
}
</div>
);
}
inputChange(e){
console.log(e.target.value)
}
}
const stateToProps=(state)=>{
return {
inputValue : state.inputValue,
list:state.list
}
}
const stateToDispatch=(dispatch)=>{
return {
inputChange(e){
let action={
type:'input_change',
value:e.target.value
}
dispatch(action)
},
addItem(){
let action={
type:'add_item',
}
dispatch(action)
},
deleteItem(index){
console.log(index)
let action={
type:'delete_item',
value:index
}
dispatch(action)
}
}
}
export default connect(stateToProps,stateToDispatch)(ToDoList);
reducer.js
const defaultState={
inputValue:'hello',
list:[]
}
export default (state = defaultState, action)=>{
if(action.type === 'input_change'){
let newState = JSON.parse(JSON.stringify(state))
newState.inputValue = action.value
return newState
}
if(action.type === 'add_item'){
let newState = JSON.parse(JSON.stringify(state))
newState.list.push(newState.inputValue)
newState.inputValue=''
return newState
}
if(action.type === 'delete_item'){
let newState = JSON.parse(JSON.stringify(state))
newState.list.splice(action.value,1)
return newState
}
return state
}