在哪里写axios post请求插入todo到数据库中。如果我在componentDidUpdate()中写入axios post请求,每当点击todo_completed状态的复选框时,它将插入到数据库中。重复记录保持真假。我不明白的地方来电来邮请求todoApp.jsx 这里是我的代码 todoapp.jsx在哪里使用axios post请求在reactJs中插入我的待办事项?
var React = require('react');
var TodoSearch = require('TodoSearch');
var AddTodo = require('AddTodo');
var TodoList = require('TodoList');
var axios= require('axios');
var TodoApp=React.createClass({
getInitialState:function(){
return{
todo_completed:false,
strSearchText:'',
todos:[]
};
},
componentDidMount:function(){
var that=this;
axios.post('/displaytodo').then(function (response){
console.log("display");
var todos=response.data;
console.log(todos);
that.setState({
todos:response.data
});
}).catch(function (error){
console.log(error);
});
},
componentDidUpdate:function(){
var todo_text="";
var todo_completed="";
this.state.todos.forEach(function(todo){
todo_text= todo.todo_text;
todo_completed=todo.todo_completed;
});
//insert todo in database
axios.post('/addtodo',{
todo_text:todo_text,
todo_completed:todo_completed
}).then(function (response) {
console.log("data");
}).catch(function (error) {
console.log(error);
});
},
handleAddTodo:function(todo_text){
alert("new todo "+todo_text);
//insert query needed to add todo
this.setState({
todos:[
...this.state.todos,
{
todo_text:todo_text,
todo_completed:false
}
]
});
},
handleToggle:function(todo_id){
var updatedTodos=this.state.todos.map((todo)=>{
if(todo.todo_id===todo_id){
todo.todo_completed=!todo.todo_completed;
}
return todo;
});
//update query required for completed status
this.setState({
todos:updatedTodos
})
//alert(id);
},
handleSearch:function(boolShowCompleted,strSearchText){
this.setState({
boolShowCompleted:boolShowCompleted,
strSearchText:strSearchText.toLowerCase()
});
},
render:function(){
var urlValue = this.props.params.sessionValue;
console.log(urlValue);
var {todos}=this.state;
return(
<div>
{urlValue}
<TodoSearch onSearch={this.handleSearch}/>
<TodoList todos={todos} onToggle={this.handleToggle}/>
<AddTodo onAddTodo={this.handleAddTodo}/>
</div>
)
}
});
module.exports=TodoApp;
AddTodo.jsx
var AddTodo = React.createClass({
handleSubmit: function(e) {
e.preventDefault();
var strTodoText = this.refs.strTodoText.value;
if (strTodoText.length > 0) {
this.refs.strTodoText.value = '';
this.props.onAddTodo(strTodoText);
} else {
this.refs.strTodoText.focus();
}
},
render: function() {
return (<div>
< form onSubmit = { this.handleSubmit } >
< input type = "text" ref = "strTodoText"/>
< button className = "button" > Add Todo < /button>
</form > Add todo.....
< /div>
)
}
});
您应该在handleAddTodo方法内而不是componentDidUpdate内使用您的axios请求。 – duwalanise
当我在handleAddTodo中添加axios后rrequest它包含最后添加待办事项在发布请求 – Sweety
我还没有看到您的AddTodo组件。但它应该有一个todo_text和一个按钮的输入字段。点击按钮,你应该将新输入的todo_text传递给handleAddTodo函数。 – duwalanise