在React组件的componentDidMount函数中,我将一个字符串(通过props接收)传递给一个函数,该函数对该字符串执行一些处理,并返回另一个字符串作为结果。然后,我将使用生成的字符串更新状态。
import React, { Component } from "react";
import {fun} from "../some/module";
class Comp extends Component {
state = {
data: "default value"
};
componentDidMount() {
var { str } = this.props;
var data = fun(str);
this.setState({ data });
}
render() {
return (
<p>{this.state.data}</p>
);
}
}
export default Comp;函数fun(text)的运行时间为3-4秒。它不从任何远程服务器获取任何数据,它只根据给定的字符串生成一个新的字符串。我在另一个组件上有一个此组件的React Router Link。我可以通过单击该链接来查看此组件。问题是,当我单击该链接时,它会等待,直到componentDidMount函数完成执行,然后呈现该组件。由于componentDidMount函数中的函数调用非常耗时,因此此延迟会持续3-4秒。
我希望在使用默认状态单击该链接后立即呈现此组件。在fun(text)函数完成执行后,我希望使用fun(text)返回的字符串再次呈现或更新此组件。
如何在此组件中实现此行为?应该在何时何地调用函数fun(text)
发布于 2020-10-03 23:40:36
您可以使用static getDerivedStateFromProps()而不是componentDidMount。
static getDerivedStateFromProps(nextProps,prevState) {
if(nextProps.str) {
const resultData = fun(str);
return {
data: resultData
}
}
return null
}我希望这会对你有所帮助。有关getDerivedStateFromProps()的更多信息,请访问Link
https://stackoverflow.com/questions/64185777
复制相似问题