因此,一开始我的问题是,从另一个页面(AddAlbum)重定向时,我的组件(Feed)未使用新数据(状态)更新页面。要解决此问题,我必须将componentDidUpdate()
添加到我的组件(Feed)中,以将componentDidUpdate()
中的状态设置为由Node JS API通过AddAlbum创建的数据。它的确呈现了我的新数据,但是出现了这个错误:
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 the componentWillUnmount method.
这是我来自Feed的代码:
componentDidMount() {
console.log('COMPONENT HAS MOUNTED');
let album = this.state.album;
fetch(`http://localhost:8000/albums`)
.then((response) =>
response.json())
.then((data) => {
this.setState({ album : data });
}).catch((error) => {
console.log("Error " + error)
})
}
componentDidUpdate() {
fetch(`http://localhost:8000/albums`)
.then((response) =>
response.json())
.then((data) => {
this.setState({ album : data });
}).catch((error) => {
console.log("Error " + error)
})
}
答案 0 :(得分:0)
您可以使用isMounted React模式来避免内存泄漏。
constructor(props) {
super(props);
this._isMounted = false; }
componentDidMount() {
this._isMounted = true;
this._isMounted && fetch(`http://localhost:8000/albums`)
.then((response) =>
response.json())
.then((data) => {
this.setState({ album : data });
}).catch((error) => {
console.log("Error " + error)
})
}
componentDidUpdate() {
this._isMounted && fetch(`http://localhost:8000/albums`)
.then((response) =>
response.json())
.then((data) => {
this.setState({ album : data });
}).catch((error) => {
console.log("Error " + error)
})
}
和您的componentWillUnmount
componentWillUnmount() {
this._isMounted = false;
}
答案 1 :(得分:0)
我认为最好的做法是听警告,而不是尝试更新已卸载组件的状态。
album
var置于父组件的状态,并在Feed
组件中作为prop接收数据。redux
,mobx
或context
),然后再次将album
变量放入{{1} },并在store
中作为道具接收。