对于想了解使用异步componentDidMount()好吗?的读者,本文将是一篇不可错过的文章,我们将详细介绍异步import,并且为您提供关于componentdidmount-道具类型验证、Co
对于想了解使用异步 componentDidMount() 好吗?的读者,本文将是一篇不可错过的文章,我们将详细介绍异步import,并且为您提供关于componentdidmount - 道具类型验证、ComponentDidMount 中的 ref 为 null、ComponentDidMount 异常行为、componentDidMount 或 componentWillMount 在 React-Native 中不起作用?的有价值信息。
本文目录一览:- 使用异步 componentDidMount() 好吗?(异步import)
- componentdidmount - 道具类型验证
- ComponentDidMount 中的 ref 为 null
- ComponentDidMount 异常行为
- componentDidMount 或 componentWillMount 在 React-Native 中不起作用?
使用异步 componentDidMount() 好吗?(异步import)
在 React Native 中使用componentDidMount()
作为异步函数的好习惯还是我应该避免它?
我需要从AsyncStorage
组件安装时获取一些信息,但我知道使这成为可能的唯一方法是使componentDidMount()
函数异步。
async componentDidMount() { let auth = await this.getAuth(); if (auth) this.checkAuth(auth);}
这有什么问题吗?还有其他解决方案吗?
答案1
小编典典让我们首先指出差异并确定它如何导致麻烦。
这是异步和“同步”componentDidMount()
生命周期方法的代码:
// This is typescript codecomponentDidMount(): void { /* do something */ }async componentDidMount(): Promise<void> { /* do something */ /* You can use "await" here */}
通过查看代码,我可以指出以下差异:
- 关键字:在打字稿中,这
async
只是一个代码标记。它做了两件事:- 强制返回类型为
Promise<void>
而不是void
. 如果您明确指定返回类型为非承诺(例如:void),打字稿将向您吐出一个错误。 - 允许您
await
在方法内使用关键字。
- 强制返回类型为
返回类型从更改
void
为Promise<void>
- 这意味着您现在可以这样做:
async someMethod(): Promise<void> { await componentDidMount(); }
- 这意味着您现在可以这样做:
您现在可以
await
在方法中使用关键字并暂时暂停其执行。像这样:async componentDidMount(): Promise<void> {const users = await axios.get<string>("http://localhost:9001/users");const questions = await axios.get<string>("http://localhost:9001/questions");// Sleep for 10 secondsawait new Promise(resolve => { setTimeout(resolve, 10000); });// This line of code will be executed after 10+ secondsthis.setState({users, questions});return Promise.resolve();
}
现在,他们怎么可能惹麻烦?
async
关键字是绝对无害的。- 我无法想象在任何情况下您都需要调用该
componentDidMount()
方法,因此返回类型Promise<void>
也是无害的。
调用返回类型为Promise<void>
不带await
关键字的方法与调用返回类型为 的方法没有区别void
。
componentDidMount()
由于延迟执行后没有生命周期方法似乎很安全。但是有一个问题。
假设上述this.setState({users, questions});
内容将在 10 秒后执行。在延迟时间的中间,另一个......
this.setState({users: newerUsers, questions: newerQuestions});
… 已成功执行并且 DOM 已更新。结果对用户可见。时钟继续滴答作响,10秒过去了。然后延迟this.setState(...)
执行,DOM
将再次更新,那个时候老用户和老问题。用户也可以看到结果。
async
=> 使用withcomponentDidMount()
方法非常安全(我不确定 100%)
。我是它的忠实粉丝,到目前为止,我还没有遇到任何让我头疼的问题。
componentdidmount - 道具类型验证
如果您添加了像 import UIKit
import Foundation
struct Example: Codable {
let userId: Int
let id: Int
let title: String
let completed: Bool
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func getJson(completion: @escaping (Example)-> ()) {
let urlString = "https://jsonplaceholder.typicode.com/todos/1"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) {data,res,err in
if let data = data {
let decoder = JSONDecoder()
do {
let json: Example = try! decoder.decode(Example.self,from: data)
completion(json)
}catch let error {
print(error.localizedDescription)
}
}
}.resume()
}
}
getJson() { (json) in
print(json.id)
}
}
这样的 prop 验证 isRequired
,您只会遇到未定义 prop 的问题。考虑到这一点,您只需要正确定义 propType:
PropTypes.array.isRequired
,
分解 componentDidMount 即
componentDidMount() {
{ getArticles } = this.props;
getArticles();
}
并添加
ArticlesList.propTypes = {
getArticles: PropTypes.func,articles: PropTypes.array,};
ComponentDidMount 中的 ref 为 null
如何解决ComponentDidMount 中的 ref 为 null?
我有一个 KonvaJS 阶段的参考。在ComponentDidMount中,this.stageRef.current的值为null。任何想法为什么?
我的代码如下:
import React,{ useState } from "react"
import { Stage,Layer,Rect,Text } from ''react-konva'';
import Konva from ''konva'';
class MyComponent extends React.Component {
constructor() {
super()
this.stageRef = React.createRef()
}
componentDidMount() {
// this.stageRef.current is null here!
}
render() {
return (
<>
<Stage id="canvas-text"
width={400} height={163}
className="stage"
ref={this.stageRef}>
<Layer>
<Text fontFamily=''Karla'' fontSize={24} align=''center'' width={400} y={30} text={"Hello"} />
</Layer>
</Stage>
</>
)
}
}
export default MyComponent;
解决方法
Stage
组件是一个函数组件,它将引用转发到其底层子组件。 You can inspect the sources:
export const Stage = React.forwardRef((props,ref) => {
return <StageWrap {...props} forwardedRef={ref} />;
});
您提供的一个直接示例表明 the ref
references the underlying StageWrap
component appropriately。
ComponentDidMount 异常行为
setInterval() 方法以指定的时间间隔(以毫秒为单位)调用函数或计算表达式
这就是 setInterval 正在做的事情。它可用于以一定的间隔重复某些任务。如果您只想执行一次,请改用 setTimeout()。
setInterval ReadMore
setTimeout ReadMore
setInterval 是一个函数,它会每隔一段时间不断调用自己,在本例中为 1 秒。 componentDidMount 的作用是在组件挂载后执行一次其中的代码。
所以在这种情况下,componentDidMount 调用了 setInterval 一次,setInterval 每隔 1 秒调用一次,直到您在 componentWillUnmount 中将其清除。
componentDidMount 或 componentWillMount 在 React-Native 中不起作用?
componentDidMount
和 componentWillMount
仅适用于基于类的 React 组件;您在这里拥有的是一个功能组件。您可以使用 useEffect
钩子来完成相同的操作。
useEffect(() => {
getWeather();
},[]);
注意 this
不存在于函数组件中;您可以在声明后直接调用该函数。
如果您之前没有使用过 useEffect
,您可能对数组作为第二个参数有疑问。如果它为空,它将在 mount 上运行,并将运行您从 unmount 时的第一个参数返回的内容。如果您想再次运行您的效果,请在数组中添加一个依赖项。
ComponentDidMount 只能在类组件中工作。使用 useEffect React hook 可以毫无问题地达到相同的效果
今天关于使用异步 componentDidMount() 好吗?和异步import的介绍到此结束,谢谢您的阅读,有关componentdidmount - 道具类型验证、ComponentDidMount 中的 ref 为 null、ComponentDidMount 异常行为、componentDidMount 或 componentWillMount 在 React-Native 中不起作用?等更多相关知识的信息可以在本站进行查询。
本文标签: