简体   繁体   English

React Native useEffect 和 useState 显示受控 TextInput 上的先前状态

[英]React Native useEffect and useState showing previous state on controlled TextInput

I am getting a very strange issue with React Native useState and useEffect and I can't work it out.我遇到了 React Native useState 和 useEffect 一个非常奇怪的问题,我无法解决。 I've got a simple form but have striped down all the components to one TextInput我有一个简单的表单,但已将所有组件TextInput为一个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

How useEffect should work in my opinion here is printing the current state each time eg在我看来, useEffect应该如何工作是每次打印当前状态,例如

// First Render - Text Input 'P'
1: {firstName: "P"}
2: {firstName: "P"}

// Second Render - Text Input 'Pe'
1: {firstName: "Pe"}
2: {firstName: "Pe"}

etc..

But what I get is但我得到的是

// First Render - Text Input 'P'
1: {firstName: "P"}

// Second Render - Text Input 'Pe'
2: {firstName: "P"}
1: {firstName: "Pe"}

So I'm getting a mixture of states (previous and old)所以我得到了混合状态(以前的和旧的)

per the behavior you had, it looks like you return the second console.log as cleanup function in the useEffect.根据您的行为,您似乎将第二个 console.log 作为 useEffect 中的清理函数返回。 it's very odd if you didn't.如果你没有,那很奇怪。

that's why I said add a semicolon at end.这就是为什么我说在最后加一个分号。 It's possible useEffect implictly return your second console.log as a cleanup function, because you don't have a semicolon at end of your 1st console.log? useEffect 可能会隐式地返回您的第二个 console.log 作为清理函数,因为您的第一个 console.log 末尾没有分号? I'm just guessing.我只是猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM