为什么不能实现增加数据,然后输入框清空?
TodoList.js
import React, { Component } from 'react';
import 'antd/dist/antd.css'
import { Input,Button,List } from 'antd'
import store from './store'
class TodoList extends Component {
constructor(props) {
super(props);
this.state=store.getState()
this.changeInputValue=this.changeInputValue.bind(this)
this.storeChange=this.storeChange.bind(this)
this.clickBtn=this.clickBtn.bind(this)
store.subscribe(this.storeChange)
}
render() {
return (
<div style={{margin:'10px'}}>
<div>
<Input
placeholder={this.state.inputValue}
style={{width:'200px',marginRight:'10px'}}
onChange={this.changeInputValue}
/>
<Button
type='primary'
onClick={this.clickBtn}
>增加</Button>
</div>
<div style={{margin:'10px',width:'300px'}}>
<List
bordered
dataSource={this.state.list}
renderItem={item=>(
<List.Item >{item}</List.Item>)}
/>
</div>
</div>
);
}
changeInputValue(e){
const action={
type:'changeInput',
value:e.target.value
}
store.dispatch(action)//通过dispatch方法将action传给store
}
storeChange(){
this.setState(store.getState())
}
clickBtn(e){
const action={
type:'addItem'
}
store.dispatch(action)
console.log(this.state.inputValue)
}
}
export default TodoList;
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import TodoList from './TodoList'
ReactDOM.render(<TodoList/>,document.getElementById('root'))
store/index.js
import {createStore} from 'redux'//引入createState方法
import reducer from './reducer'
const store=createStore(reducer,//创建数据存储仓库
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
export default store//暴露出去
store/reducer.js
```javascript
//reducer 管理数据
const defaultState={
inputValue:'Writing something',
list:[
'早8点开晨会,分配今天的开发工作',
'早9点和项目经理作开发需求讨论会',
'晚5:30对今日代码进行review'
]
}//默认数据
export default (state=defaultState,action)=>{//是一个方法函数,state是需要管理的数据信息
if(action.type==='changeInput'){
let newState = JSON.parse(JSON.stringify(state))//深度拷贝state,深度拷贝,原和现互不影响.这里的state是由TodoList传过来的state
newState.inputValue = action.value//要记住这里是action.value action中的值和store里的值是不一样的
return newState
}
if(action.type==='addItem'){
let newState = JSON.parse(JSON.stringify(state))//深度拷贝state,深度拷贝,原和现互不影响
newState.list.push(newState.inputValue) //这样也可以 [...newState.list,newState.inputValue]
newState.inputValue = ''
return newState
}
return state
}
因为TodoList.js中是
placeholder={this.state.inputValue}
所以不能清空输入框,改成value就好了