[英]Time consuming function call in componentDidMount of React component
In the componentDidMount function of my React component, I am passing a string (which is received through props) to a function that performs some processing on that string and returns me another string as a result.在我的 React 组件的 componentDidMount 函数中,我将一个字符串(通过 props 接收)传递给一个函数,该函数对该字符串执行一些处理并作为结果返回另一个字符串。 Then I am updating the state using that resulting string.
然后我使用结果字符串更新状态。
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;
The function fun(text)
runs up to 3 - 4 second.函数
fun(text)
最多运行 3 - 4 秒。 It doesn't fetch any data from any remote server, it only generates a new string based on the given string.它不会从任何远程服务器获取任何数据,它只会根据给定的字符串生成一个新字符串。 I have a React Router Link of this component on another component.
我在另一个组件上有这个组件的 React Router Link。 I can view this component by clicking on that link.
我可以通过单击该链接来查看该组件。 The problem is when I click on that link, it waits until the componentDidMount function finishes execution and then it renders this component.
问题是当我单击该链接时,它会等待 componentDidMount 函数完成执行,然后呈现该组件。 Because of that time-consuming function call in the componentDidMount function, this delay lasts for 3 - 4 seconds.
由于 componentDidMount 函数中的耗时函数调用,此延迟会持续 3 - 4 秒。
I want to render this component immediately after clicking that link using the default state.我想在使用默认状态单击该链接后立即呈现此组件。 And after
fun(text)
function finishes its execution, I want to render again or update this component using the string returned by fun(text)
.在
fun(text)
函数完成执行后,我想使用fun(text)
返回的字符串再次渲染或更新此组件。
How can I achieve this behaviour in this component?我怎样才能在这个组件中实现这种行为? When and where I should call the function
fun(text)
?我应该何时何地调用函数
fun(text)
?
You can use static getDerivedStateFromProps()
instead of componentDidMount
.您可以使用
static getDerivedStateFromProps()
而不是componentDidMount
。
static getDerivedStateFromProps(nextProps,prevState) {
if(nextProps.str) {
const resultData = fun(str);
return {
data: resultData
}
}
return null
}
I hope It'll be helpful.我希望它会有所帮助。 For More Info about
getDerivedStateFromProps()
Here is the Link有关
getDerivedStateFromProps()
更多信息这里是链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.