ListAllPost.js 代码--------------------------------
import React, { Component } from 'react';
import axios from 'axios';
import {Link} from 'react-router-dom';
const APIKEY = "loc";
let URL;
class ListAllPost extends Component{
constructor(props){
super(props);
this.state = {
allPostData : []
}
}
componentWillMount(){
URL = `http://reduxblog.herokuapp.com/api/posts?${APIKEY}`;
axios.get(URL).then((resp)=>{
this.setState({
allPostData : resp.data
});
});
}
onClickDelete(e,postId){
console.log(postId); // undefined // i am expecting the value of id here .
URL = `http://reduxblog.herokuapp.com/api/posts/${postId}?${APIKEY}`;
axios.delete(URL).then((resp)=>{
console.log("deleted"+resp.status)
});
}
render(){
if(!this.state.allPostData){
return <div>Loading...</div>
}
let listItem = this.state.allPostData.map((post)=>{
let postId = post.id;
return(
<li key = {postId}>
<Link to = {{pathname : `/viewPost/${postId}`}} >
{post.title}
</Link>
<i onClick = {(postId)=>this.onClickDelete(postId)}>Delete</i>
</li>
);
});
return(<div>
<ul>
{listItem}
</ul>
</div>
);
}
}
export default ListAllPost;
在上面的渲染函数中的代码中......我正在生成一个列表项,它有两个子元素,比如 (Link) 标签和标签。我需要实现一个功能,比如当我点击标签时我需要重定向,而当我单击 delete () 标记必须删除列表项。在 onClick 函数中,当我尝试将 postId 作为参数传递给 onClickDelete 函数时,它没有按我预期的那样传递..我知道我们已经使用了大括号调用 eventHandlerfunction ...我也试过像 Delete这样调用...这也不起作用..首先实现这个功能是正确的方法吗......?请帮帮我。我只是在学习反应使用一些演示项目..对此的任何帮助都会非常有帮助。
首先Link
你可以做
<Link to={`/viewPost/${postId}`}>{post.title}</Link>
随着onClick
事件。你应该做:
...
onClickDelete = (postId) => {
// Axios logic here.
// You should call some kind of state-change inside of the component,
// so the component knows that it has to be updated. Like deleting this post
// from this.state.allPostData.
}
...
render() {
...
<i onClick={() => this.onClickDelete(postId)}>Delete</i>
...
}
如果像 onClick 事件那样直接传递函数,则只传递e
参数,该参数是执行事件时onChange始终提供的事件函数onClick
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句