Javascript e、 preventDefault()不是Reactjs中的函数,请使用bind
我是个新手,我想在用户单击时传递一个a值作为参数,也可以使用preventDefault,我发现建议使用bind我将其用作下面的代码,但没有解决我的问题,它给了我错误Javascript e、 preventDefault()不是Reactjs中的函数,请使用bind,javascript,reactjs,Javascript,Reactjs,我是个新手,我想在用户单击时传递一个a值作为参数,也可以使用preventDefault,我发现建议使用bind我将其用作下面的代码,但没有解决我的问题,它给了我错误类型错误:e.preventDefault不是一个函数 constructor(props){ super(props) this.state={ headline:'', articles:[], article:[], } } componentDidMo
类型错误:e.preventDefault不是一个函数
constructor(props){
super(props)
this.state={
headline:'',
articles:[],
article:[],
}
}
componentDidMount(){
axios.get("http://127.0.0.1:5000/api/v1/news")
.then(res=>{this.setState({articles:res.data})}
)
}
browse = (e,id) => {
console.log(e)
e.preventDefault()
console.log(id)
axios.get("http://127.0.0.1:5000/api/v1/news/"+id)
.then(res=>{this.setState({article:res.data,});console.log(res.data)})
}
实际上,以这种方式编写onClick,就是在呈现组件时调用函数,传递的“e”不是事件,因此e.preventDefault()不是函数
要绑定onClick而不在运行时调用它并传递“event”,可以使用以下格式,如前所述:
这并不是说preventDefault不存在,而是仍然重新加载页面。请先测试将行“e.preventDefault()”放在“console.log(e)”之前,并让我知道结果。在重新加载之前,下面是代码,您为什么再次调用“this.componentDidMount();”?对于梅来说,一切似乎都很好,只是添加了它,因为当它重新加载时。它给出了不存在的this.state.articles的错误。我能换一种方式吗?
Here's where i use the browse method
{this.state.articles.map(art=> {return (
<tr>
<td><a href={art.url}>{art.headline}</a></td>
<td>{art.topic}</td>
<td>{art.author}</td>
<td><button onClick ={this.browse.bind(this,art._id.$oid)} > Browse </button></td>
</tr>
)})}
×
TypeError: e.preventDefault is not a function
App.browse
src/App.js:36
33 | }
34 |
35 | browse = (e,id) => {
> 36 | e.preventDefault()
37 | axios.get("http://127.0.0.1:5000/api/v1/news/"+id)
38 | .then(res=>{this.setState({article:res.data,});console.log(res.data)})
39 | }
View compiled
onClick={(e) => this.browse(e, id)}