gpt4 book ai didi

javascript - React如何正确调用函数来响应

转载 作者:行者123 更新时间:2023-12-02 22:42:18 24 4
gpt4 key购买 nike

我正在使用 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>
)
}
}

我想 chop 帖子的文本,以便帖子仅显示 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>

但是我想使用在文本上调用 get 的函数来完成此操作,因此我在名为 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

如何调用该函数并正确执行 chop ?

最佳答案

您尚未将 truncatetext 绑定(bind)到组件:that causes problems with the context 。在构造函数中,您可以使用 this.truncatetext = this.truncatetext.bind(this):

  constructor(props) {
super(props);
this.state = {
posts: []
};
this.truncateText = this.truncateText.bind(this);
}

关于javascript - React如何正确调用函数来响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58546643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com