我正在尝试学习react redux,并创建了一个小型的待办事项应用程序,该应用程序的后端为 REST服务器
大部分部分已实现,但是,我无法理解如何将值从输入框传递给其余的API调用。我能够在redux状态下成功存储inputbox的值。
我正在使用react-thunk作为中间件来处理API调用。
容器
import { connect } from 'react-redux'
import {toggleAddTodoDialog, addNewTodo, handleChange} from '../actions'
import AddTodoDialog from '../components/add_todo_dialog';
class AddTodoContainer extends Component {
render() {
return (
<div>
<AddTodoDialog toggleAddTodoDialog={this.props.toggleAddTodoDialog}
addNewTodo = {this.props.addNewTodo}
newTodoList = {this.props.newTodoList}
handleChange = {this.props.handleChange}
is_add_todo_dialog_opened={this.props.is_add_todo_dialog_opened}/>
</div>
)
}
}
const mapStateToProps = (state) => {
return state
}
const bindActionsToDispatch = dispatch =>
(
{
toggleAddTodoDialog : (e) => dispatch(toggleAddTodoDialog(e)),
handleChange: (e) => dispatch(handleChange(e)),
addNewTodo : (e) => addNewTodo(e)
}
)
export default connect(mapStateToProps, bindActionsToDispatch)(AddTodoContainer)
组件
export default class AddTodoDialog extends Component {
toggleAddTodoDialog = (e) => {
this.props.toggleAddTodoDialog(!this.props.is_add_todo_dialog_opened)
}
addNewTodo = (e) => {
this.props.addNewTodo()
this.toggleAddTodoDialog(e)
}
handleChange = (e) => {
this.props.handleChange(e)
}
render() {
return (
<div>
<Button color="primary" onClick={this.toggleAddTodoDialog}>Add new Todo</Button>
<Modal isOpen={this.props.is_add_todo_dialog_opened} >
{/* <Modal isOpen={false} > */}
<ModalHeader toggle={this.toggleAddTodoDialog}>Modal title</ModalHeader>
<ModalBody>
<FormGroup >
<Label for="Title">Task </Label>
<Input name="task"
value={this.props.newTodoList.task}
onChange={this.handleChange} />
</FormGroup>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={this.addNewTodo}>OK</Button>{' '}
<Button color="secondary" onClick={this.toggleAddTodoDialog}>Cancel</Button>
</ModalFooter>
</Modal>
</div>
);
}
动作
export function addNewTodo() {
console.log("addNewTodo")
return function (dispatch) {
axios.post("http://localhost:5001/todos", 'task=' + this.props.addNewTodo.task)
.then(response => {
dispatch(_addTodoAction(response.data))
})
}
}
export function _addTodoAction(todos) {
console.log("_addTodoAction")
return {
type: 'ADD_TODO',
todos: todos
}
}
export function handleChange(event){
console.log("handleChange "+event)
return{
type: 'HANDLE_CHANGE',
event: event
}
}
减速器
case 'ADD_TODO':
console.log(action)
return {
...state,
todos: action.todos
}
答案 0 :(得分:0)
您正在这样调度:
addNewTodo : (e) => addNewTodo(e)
但是您的操作不包含任何参数:
export function addNewTodo() {
console.log("addNewTodo")
return function (dispatch) {
axios.post("http://localhost:5001/todos", 'task=' + this.props.addNewTodo.task)
.then(response => {
dispatch(_addTodoAction(response.data))
})
}
}
如果需要输入值的值:
handleChange = (e) => {
this.props.handleChange(e.target.value)
}
然后分派:
handleChange: (value) => dispatch(handleChange(value)),
然后执行操作:
export function handleChange(value) {
...