上一篇中我們已經將Action與如何處理Action的Reducer建立好了,接下來將整個TodoList專案透過以下順序建立:
import React from 'react';
import { connect } from 'react-redux';
import { addTodo } from '../Store/Action/Action';
class AddTodo extends React.Component
{
state = {
value:""
}
//====================================
handleChange = (e) => {
const _value = e.target.value;
this.setState({
value:_value
})
};
//====================================
handleSubmit = (e) => {
const inputValue = this.state.value;
//Step 1 : 取消預設行為
e.preventDefault()
//Step 2 : 判斷Input是否為空
if(!this.state.value.trim()){
return
}
//Step 3 : 發送"ADD_TODO"到Reducer新增一個新的todo物件
this.props.dispatch(addTodo(inputValue));
//Step 4 : 清空input內容
this.setState({
value:""
});
};
//====================================
render()
{
return(
<div>
<form onSubmit={ this.handleSubmit }>
<input
value={this.state.value}
onChange={ this.handleChange }
/>
<button type="submit">Add Todo</button>
</form>
</div>
)
}
}
export default connect(
//利用mapStateToProps在state改變時就會觸發的特性,觀察Reducer是否有新增新的state
(state) => {console.log(state)}
)(AddTodo);
透過mapStateToProps可以確認,確實有新的State被創建出來,並且text也是我們輸入的數值
參考資料 :
從Redux 的作者學習它