我在使用React Native useState和useEffect时遇到了一个非常奇怪的问题,我解决不了这个问题。我得到了一个简单的表单,但是已经将所有组件简化为一个TextInput
import React, { useState, useEffect } from 'react'
import { TextInput } from 'react-native'
const InputExample = () => {
const [name, setName] = useState('')
useEffect(() => {
console.log('1:', name)
console.log('2:', name)
}, [name])
return (
<TextInput
placeholder="First name"
maxLength={100}
value={name}
onChangeText={(text) => setName(text)}
style={{ margin: 20, fontSize: 20, borderColor: 'black', borderWidth: 1, padding: 10 }}
/>
)
}
export default InputExample在我看来,useEffect的工作原理是每次打印当前状态。
// First Render - Text Input 'P'
1: {firstName: "P"}
2: {firstName: "P"}
// Second Render - Text Input 'Pe'
1: {firstName: "Pe"}
2: {firstName: "Pe"}
etc..但我得到的是
// First Render - Text Input 'P'
1: {firstName: "P"}
// Second Render - Text Input 'Pe'
2: {firstName: "P"}
1: {firstName: "Pe"}所以我得到了一个混合的状态(以前的和以前的)
发布于 2020-01-15 00:47:26
根据您的行为,看起来您在useEffect中将第二个console.log作为清理函数返回。如果你没有,那就太奇怪了。
这就是为什么我说在结尾加一个分号。useEffect可能会隐含地返回您的第二个console.log作为清理函数,因为您的第一个console.log的末尾没有分号?我只是在猜测。
https://stackoverflow.com/questions/59737879
复制相似问题