【发布时间】:2020-06-06 18:19:03
【问题描述】:
我是 react-native 的新手,学习完整的代码。但我无法理解“const”在导出之前和渲染之后的区别。例如:
const { height, width } = Dimensions.get("window");
export default class App extends React.Component {
state = {
newToDo: ""
};
render() {
const { newToDo } = this.state;
我之所以问这个是因为我的第一个初始化不是“导出默认类 App 扩展 React.Component {”而是“导出默认函数 App(){”。所以我不能分配 const 或分配它,它会导致显示消息的错误
TypeError:undefined is not an object (evalating 'this.state')
这是我的代码:
import React from "react";
import {
StyleSheet,
Text,
View,
Dimensions,
TextInput,
Platform,
ScrollView
} from "react-native";
import ToDo from "./ToDo";
const { height, width } = Dimensions.get("window");
export default function App() {
const state = {
newToDo: ""
};
const { newToDO } = this.state;
return (
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.title}>Good or Bad</Text>
<Text style={styles.subTitle}>Check Daily your habit</Text>
</View>
<View style={styles.content}>
<Text style={styles.contentTitle}>To Do List</Text>
<TextInput
style={styles.input}
placeholder={"New to do"}
value={newToDO}
onChangeText={this._controllNewToDo}
returnKeyType={"done"}
autoCorrect={false}
/>
<ScrollView>
<ToDo />
</ScrollView>
</View>
</View>
);
_controllNewToDo = text => {
this.setState({
newToDO: text
});
};
}
【问题讨论】:
-
你的 react-native 版本是什么
-
如果你的 react-native 版本支持钩子,那么你必须使用 useState 钩子来更新状态
-
“依赖”:{“expo”:“~36.0.0”,“react”:“~16.9.0”,“react-dom”:“~16.9.0”,“react -native": "github.com/expo/react-native/archive/sdk-36.0.0.tar.gz", "react-native-web": "~0.11.7" }, "devDependencies": { "babel-preset-expo": "~8.0.0", "@babel/核心": "^7.0.0"