Javascript 为什么onclick函数的类型错误?-反应
我正在开发一个应用程序,用于从API获取帖子并加载帖子。除了Javascript 为什么onclick函数的类型错误?-反应,javascript,reactjs,Javascript,Reactjs,我正在开发一个应用程序,用于从API获取帖子并加载帖子。除了gotopost函数外,一切都正常。呈现此错误后出现TypeError:无法读取未定义的属性“gotopost” 但是我不知道为什么会发生这种情况,虽然我绑定了这个函数,并在render()函数上面声明了这个函数 下面是代码 import React, { Component } from 'react'; import './App.css'; class Todos extends React.Component {
gotopost
函数外,一切都正常。呈现此错误后出现TypeError:无法读取未定义的属性“gotopost”
但是我不知道为什么会发生这种情况,虽然我绑定了这个函数,并在render()函数上面声明了这个函数
下面是代码
import React, { Component } from 'react';
import './App.css';
class Todos extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
posts: [],
singleLoaded: false,
singlepost: []
}
this.fetchposts = this.fetchposts.bind(this);
}
fetchposts(){
fetch("http://smashingdevs.com/wp-json/wp/v2/posts/")
.then((response) => {
return response.json();
})
.then((posts) => {
this.setState({
isLoaded: true,
posts: posts
});
});
}
render() {
let container;
if(this.state.isLoaded){
container = <Allposts posts={this.state.posts}/>;
}else if(this.state.singleLoaded){
container = <Singleposts />;
}
return (
<div>
<h2>Hello there</h2>
<button onClick={this.fetchposts}>
fetch posts
</button>
{container}
</div>
);
}
}
class Allposts extends React.Component{
constructor(props){
super(props);
}
gotopost(){}
render(){
return (<div className="row mt-5">
{
this.props.posts.map(function(post){
return <div className="col-md-6 mb-2" key={post.id}>
<div className="card" >
// Problem is here on onClick
<a href={post.link} onClick={this.gotopost.bind(this)} className="btn btn-primary">Go somewhere</a>
</div>
</div>
})
}
</div>
)
}
}
class Singleposts extends React.Component{
}
export default Todos;
import React,{Component}来自'React';
导入“/App.css”;
类Todos扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
错误:null,
isLoaded:false,
员额:[],
单加载:false,
singlepost:[]
}
this.fetchposts=this.fetchposts.bind(this);
}
fetchposts(){
取回(“http://smashingdevs.com/wp-json/wp/v2/posts/")
。然后((响应)=>{
返回response.json();
})
。然后((帖子)=>{
这是我的国家({
isLoaded:是的,
职位:职位
});
});
}
render(){
让容器;
if(this.state.isLoaded){
容器=
})
}
)
}
}
类Singleposts扩展了React.Component{
}
导出默认TODO;
这是JS的常见错误。当您转到内部函数时,该范围内的var此
不再在类外。解决方法是将此分配给方法顶部的另一个变量
render(){
const self=这个;
返回(
{
this.props.posts.map(函数(post)){
返回
//用self代替这个
})
}
)
}
此
将不是您在赋予映射的函数中所期望的。您可以将函数绑定到此
,也可以使用箭头函数使用周围的词法范围,而此
将是您想要的
class Allposts extends React.Component {
gotopost() {}
render() {
return (
<div className="row mt-5">
{this.props.posts.map(post => {
return (
<div className="col-md-6 mb-2" key={post.id}>
<div className="card">
<a
href={post.link}
onClick={this.gotopost.bind(this)}
className="btn btn-primary"
>
Go somewhere
</a>
</div>
</div>
);
})}
</div>
);
}
}
class Allposts扩展React.Component{
gotopost(){}
render(){
返回(
{this.props.posts.map(post=>{
返回(
);
})}
);
}
}
使用箭头功能:
this.props.posts.map((post) => {