javascript - 如何同时使用类和道具 javascript react native
问题描述
我正在使用const
,以便我可以navigation
为我的屏幕提供道具。现在,我需要实现componentDidMount()
,但我必须切换到一个类来做到这一点。我怎样才能拥有它,以便我可以同时拥有navigation
道具和类Component
功能?
代码示例:
导航.ts
import { ParamListBase, RouteProp } from "@react-navigation/native";
import { StackNavigationProp } from '@react-navigation/stack';
export interface StackNavigationProps<
ParamList extends ParamListBase,
RouteName extends keyof ParamList = string
> {
navigation: StackNavigationProp<ParamList, RouteName>;
route: RouteProp<ParamList, RouteName>;
onPress: () => void;
}
export type Routes = {
Screen1: undefined;
Screen2: undefined;
Screen3: undefined,
};
屏幕1.tsx
const Screen1 = ({ navigation }: StackNavigationProps<Routes, "Screen1">) => {
...
}
如何结合上面和下面的内容来包含navigation
道具和React.Component
?
class Screen1 extends React.Component {
componentDidMount() {
...
}
}
解决方案
如果你想拥有componentDidMount方法,你不必使用类组件,你可以在函数式编程中使用以下代码:
React.useEffect(()=>{
//Writing code here , have behavior like componentDidMount
return () => {
//Cleaning up , it's have behavior like componentWillUnmount
}
} , []); //If you add dependency , it's have behavior like componentDidUpdate
推荐阅读
- c# - 如何将 IFileFormCollection 中的多个上传文件链接到相应的复杂模型字段?
- python - 用 Python 实现形态桥接
- generics - 在 F# 中是否可以内联和覆盖?有哪些替代方案?
- node.js - 如果现有数组中列出了另一个属性,如何在 Mongoose 中投影一个新的布尔字段?
- reactjs - 将三元运算符与 React 和 Typescript 一起使用的正确方法是什么
- kubernetes - Google Cloud Endpoints 不限制对我的 API 的访问
- java - Spring Kafka生产者不能异步工作
- python - 更改 Flask 和自定义装饰器的顺序会破坏自定义装饰器
- postgresql - 何时对 Ecto 的“on_delete”使用“nothing”或“restrict”?
- python - 我可以使用 DRF 覆盖 ApiView 中单个请求类型的全局身份验证吗?