如何将 $.get()
中的 response.status
保存到 React 变量 this.posts
中?
当我尝试从 $.get()
中访问 this.posts
时,它返回 undefined
。
import React, { Component } from 'react';
import $ from 'jquery';
class MediumPosts extends Component {
constructor(props) {
super(props);
this.posts = [];
}
fetchPosts = () => {
var data = {
rss_url: 'https://medium.com/feed/tradecraft-traction'
};
$.get('https://api.rss2json.com/v1/api.json', data, (response) => {
if (response.status == 'ok') {
console.log(response.items);
this.posts = response.items; // Undefined
}
});
}
componentDidMount() {
this.fetchPosts();
}
render() {
return (
<ul>
{this.posts.map(function(item, i) {
return (
<li key={item.guid}>
<h4>{item.title}</h4>
<time>{item.pubDate}</time>
</li>
)
})}
</ul>
)
}
}
export default MediumPosts;
最佳答案
基本上,您应该保持您的帖子
处于状态。
当值随时间变化时,它应该处于状态
(如果它不是来自父组件),然后您只需更新它。
因此,您的代码将如下所示:
class MediumPosts extends Component {
constructor(props) {
super(props);
// init state
this.state = {
posts: [],
}
}
fetchPosts = () => {
// because you are pass arrow function in the callback we have to save `this`.
// or you can create callback function in the component and pass it
const self = this;
const data = {
rss_url: 'https://medium.com/feed/tradecraft-traction'
};
$.get('https://api.rss2json.com/v1/api.json', data, response => {
if (response.status == 'ok') {
self.setState({posts: response.items});
}
});
}
componentDidMount() {
this.fetchPosts();
}
render() {
return (
<ul>
{this.state.posts.map(function(item, i) {
return (
<li key={item.guid}>
<h4>{item.title}</h4>
<time>{item.pubDate}</time>
</li>
)
})}
</ul>
)
}
}
export default MediumPosts;
无论如何,我建议你在 ReactJS 项目中摆脱 jQuery
。相反,使用 axios .
希望对您有所帮助。
关于jquery - 如何保存 jQuery Get 响应到 React 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49420637/