如何在渲染组件之前正确地获得反应新鲜状态?

How to properly get a react fresh state before rendering the component?

如果答案很明显,我很抱歉。我可能错过了这样做的模式...

我有这种架构(当然更复杂): 一个组件(这里是一个按钮)有同时调用函数和设置状态。

当然,这个例子不起作用,因为要显示的状态 word 在调用 speak() 函数之前没有定义。

最好的方法是什么?

const Speaker = () => {
  const [word, setWord]=  useState ("nothing")

  const speak = () => {
    console.log(word)
    ...
  }

  const speakDirectly = () => {
    setWord("hello")
    speak() // say "nothing" instead of "hello" 
  }

  const prepareWord = (wordToPrepare) => {
    setWord(wordToPrepare)
  }

  return (
    <>
    <p>Thinking word : {word} </p>
    <button onClick={() =>prepareWord('Goodbye')} >Prepare to say "Goodbye"</button>
    <button onClick={() =>prepareWord('Goodnight')} >Prepare to say "Goodnight"</button>
    ----
    <button onClick={() =>speak()} >Say Hello</button> 
    <button onClick={() =>speakDirectly('hello')} >Say Hello</button> 
    </>
  )

}

React 中是否存在解决此行为的模式?

我想避免像这样更新我的功能

const Speaker = () => {
  const [word, setWord]=  useState ("nothing")

  const speak = (directWord) => {
        let wordToSay = directWord || word
        console.log(word)
        ...
   }
   const speakDirectly = (directWord) => {
        setWord(directWord)
        speak(directWord) 
   }
    ...

你可以这样做。为您的话语和您的直接话语设定一个状态。对您的直接词使用效果以在更新时触发说话,但为您准备好的词在点击时调用说话。

const Speaker = () => {
  const [preparedWord, setPreparedWord]=  useState();
  const [directWord, setDirectWord]=  useState();

  const speak = (word) => {
    console.log(word)
    ...
  }

  useEffect(() => directWord && speak(directWord), [directWord]);

  return (
    <>
    <p>Thinking word : {preparedWord} </p>
    <button onClick={() => setPreparedWord('Goodbye')} >Prepare to say "Goodbye"</button>
    <button onClick={() => setPreparedWord('Goodnight')} >Prepare to say "Goodnight"</button>
    ----
    <button onClick={() => speak(preparedWord)} >Speak</button> 
    <button onClick={() => setDirectWord('hello')} >Say Hello</button> 
    </>
  )

}

更新

想一想,除非你需要直接词进入你的状态,否则你也可以去掉那部分,在将它传递给函数时调用 speak 就可以了。

const Speaker = () => {
  const [preparedWord, setPreparedWord]=  useState();

  const speak = (word) => {
    console.log(word)
    ...
  }

  return (
    <>
    <p>Thinking word : {preparedWord} </p>
    <button onClick={() => setPreparedWord('Goodbye')} >Prepare to say "Goodbye"</button>
    <button onClick={() => setPreparedWord('Goodnight')} >Prepare to say "Goodnight"</button>
    ----
    <button onClick={() => speak(preparedWord)} >Speak</button> 
    <button onClick={() => speak('hello')} >Say Hello</button> 
    </>
  )

}