javascript - React 如何正确调用函数来响应
问题描述
我正在使用 React 和 MongoDB 制作博客。我从 MongoDB 检索数据,这是我的组件:
import React, { Component } from 'react';
import axios from 'axios';
export default class Post extends Component {
constructor(props) {
super(props);
this.state = {
posts: []
};
}
truncateText = text => {
return text.substring(0, 500) + "...";
}
allPosts = () => {
return this.state.posts.map(function(astroPost, i){
return <div class="post-container">
<img className="post-info-container__image" src={astroPost.picture} alt=""/>
<div className="post" posts={astroPost} key={i}>
<div class="post-container__text">
<h2>{astroPost.title}</h2>
<p className="date">{astroPost.date}</p>
<p className="post-info-container__text">{this.truncateText(astroPost.postContent)}</p>
<button>Read more</button>
</div>
</div>
</div>
})
}
componentDidMount() {
axios.get('http://localhost:4000/')
.then(response => {
this.setState({posts: response.data})
console.log(response)
})
.catch(function(error) {
console.log(error)
})
}
render() {
return (
<div>
{ this.allPosts() }
</div>
)
}
}
我想截断帖子的文本,以便帖子仅显示 500 个符号。我通过这样做实现了这一点:
return this.state.posts.map(function(astroPost, i){
return <div class="post-container">
<img className="post-info-container__image" src={astroPost.picture} alt=""/>
<div className="post" posts={astroPost} key={i}>
<div class="post-container__text">
<h2>{astroPost.title}</h2>
<p className="date">{astroPost.date}</p>
<p className="post-info-container__text">{astroPost.postContent.substring(0, 500) + "..."}</p>
<button>Read more</button>
</div>
</div>
</div>
但是我想用一个在文本上调用的函数来做,所以我在一个名为 truncateText 的函数中保留了相同的逻辑,但是当我这样调用它时:
return this.state.posts.map(function(astroPost, i){
return <div class="post-container">
<img className="post-info-container__image" src={astroPost.picture} alt=""/>
<div className="post" posts={astroPost} key={i}>
<div class="post-container__text">
<h2>{astroPost.title}</h2>
<p className="date">{astroPost.date}</p>
<p className="post-info-container__text">{astroPost.postContent.truncateText()}</p>
<button>Read more</button>
</div>
</div>
</div>
})
}
它说TypeError: astroPost.postContent.truncateText is not a function
如何调用该函数并正确执行截断?
解决方案
您没有绑定truncatetext
到组件:这会导致 context 出现问题。在构造函数中,您可以使用this.truncatetext = this.truncatetext.bind(this)
:
constructor(props) {
super(props);
this.state = {
posts: []
};
this.truncateText = this.truncateText.bind(this);
}
推荐阅读
- java - 如何在 Java 中解决“repeatSeparator”问题而没有循环?
- javascript - iOS 设备上的 NSInvalidArgumentException
- r - 如何根据 r 中的日期删除行?
- django - 如何对 Django 应用程序消耗的资源进行基准测试?
- laravel - Laravel Mix BrowserSync 没有触发
- mysql - SQL:如何选择客户营业额最大的年份和月份?
- mysql - 在 phpMyAdmin 上触发
- firebase - 用于创建用户的 Firestore 规则
- c++ - 如何概括函数调用以访问具有多种类型的模板化变量
- c# - 如果子表中的 DataValue Combobox NotExist (LINQ),则子 Cobobox 返回 Null