我想知道是否有人知道如何解决此问题。我的JavaScript中有2个函数,并且请确保将两者都绑定。如果有人知道卸载的组件的含义以及可能导致此问题的原因,将不胜感激。我的诺言结构有什么问题吗?当我在本地渲染网站时,看起来还不错。
谢谢!
E AssertionError: Error in browser console:
E webpack:///./node_modules/react-dom/cjs/react-dom.development.js? 178:25 "Warning: Can't
perform a React state update on an unmounted component. This is a no-op, but it indicates a
memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in
%s.%s" "the componentWillUnmount method" "\n in Likes (created by Post)"
我的代码:
import React from 'react';
import PropTypes from 'prop-types';
class Likes extends React.Component {
/* Display number of likes a like/unlike button for one post
* Reference on forms https://facebook.github.io/react/docs/forms.html
*/
constructor(props) {
super(props);
this.state = { num_likes: 0, logname_likes_this: false };
this.like = this.like.bind(this);
this.unlike = this.unlike.bind(this);
}
componentDidMount() {
fetch(this.props.url, { credentials: 'same-origin' })
.then((response) => {
if (!response.ok) throw Error(response.statusText);
return response.json();
})
.then((data) => {
console.log(data)
this.setState({
num_likes: data.likes_count,
logname_likes_this: data.logname_likes_this,
});
})
.catch(error => console.log(error));
}
like(event) {
event.preventDefault();
fetch(this.props.url, {
method: "POST",
header: {
'Content-Type': 'application/json'
},
})
.then(()=>{
this.setState({
num_likes: this.state.num_likes + 1,
logname_likes_this: 1,
})
})
.catch(error => console.log(error));
}
unlike(event) {
event.preventDefault();
fetch(this.props.url, {
method: "DELETE",
header: {
'Content-Type': 'application/json'
},
})
.then(()=>{
this.setState({
num_likes: this.state.num_likes - 1,
logname_likes_this: 0,
})
})
.catch(error => console.log(error));
}
render() {
let button;
if (this.state.logname_likes_this) {
button = <button onClick={this.unlike} className="like-unlike-button">unlike</button>
} else {
button = <button onClick={this.like} className="like-unlike-button">like</button>
}
return (
<div className="likes">
<p>{this.state.num_likes} like{this.state.num_likes !== 1 ? 's' : ''}</p>
{button}
</div>
);
}
}
Likes.propTypes = {
url: PropTypes.string.isRequired,
};
export default Likes;