我試圖使用反應。這裏是我的代碼 https://plnkr.co/edit/JEG6o4JCBIQWAt2A4S3r?p=preview如何使用反應在列表中添加項目?
我想在列表中添加輸入字段文本值當用戶按下按鈕添加。在我的演示中,我就點擊我想有一個add button
列表中添加的項在列表中添加項目。 你能告訴我我在做什麼錯嗎?
// Code goes here
const { createStore, bindActionCreators, applyMiddleware,combineReducers } = Redux;
const { Provider, connect } = ReactRedux;
const thunk = window.ReduxThunk.default;
const first_redux =function(state ='' ,action){
switch (action.type){
case 'ADD_ITEM':
return action.payload
default :
return state
}
}
const actions ={
addItem :function(item){
return {
type :"ADD_ITEM",
payload :item
}
}
}
var combindReducer = combineReducers({
item:first_redux
})
const store = createStore(combindReducer);
class First extends React.Component {
constructor (props){
super(props);
this.state = {
names :[],
username :''
}
this.changeEv =this.changeEv.bind(this);
this.addName =this.addName.bind(this);
}
changeEv(e){
this.setState({
username : e.target.value
})
}
addName(){
// this.state.names.push(this.state.username);
console.log(this.state);
this.props.add(this.state.username)
}
render() {
const data =[{"name":"test1"},{"name":"test2"}];
var listItems = this.state.names.map(function(d, idx){
return (<li key={idx}>{d.name}</li>)
})
return (
<div>
<input type="text" onChange ={this.changeEv}/>
<button onClick={this.addName}>add</button>
{listItems}
</div>
);
}
}
function mapStateToProps(state){
console.log('=================');
console.log(state);
return {
names: state.item,
};
console.log(this.state);
}
function mapDispatchToProps(dispatch){
return {
add:bindActionCreators(actions.addItem,dispatch)
}
}
const Appcontainer =connect(mapStateToProps,mapDispatchToProps)(First)
ReactDOM.render(
<Provider store ={store}>
<Appcontainer/>
</Provider>
,document.getElementById('root'));