【问题标题】:React useState is not picking initial state?React useState 没有选择初始状态?
【发布时间】:2021-07-22 09:28:53
【问题描述】:

我需要一个表单值来预填充来自 redux 状态的初始值:

问题是,REDUX 更新了,但是 useState 没有使用传入的初始值。

// redux
const {
    [1]: stepInfo,
    error,
    saving,
} = useSelector((state) => state.implOnboard);

// local state
// setting up initial state
// =================================================================
const [name, setName] = React.useState(stepInfo.name);
const [description, setDescription] = React.useState(stepInfo.desc);
// =================================================================

输入元素(另一个具有 value={description})

都显示空字段而不是预填充值

<input
  id="impl-name"
  placeholder="gs-sentiment-analysis-impl-1"
  value={name} // ???? using here
  onChange={(e) => {
    setName(e.target.value);
    // enable the editing status to true for this step if any state changes
    setEditingStepStatus(1, true);
  }}
/>

调试

  console.log(name, description); // prints '', ''
  console.log(stepInfo); // but this prints the actual values that I want to show

【问题讨论】:

  • 你确定redux是在初始状态设置之前设置的吗?
  • @DBS,即使后面设置了redux,它不会重新渲染组件并重新设置useState上的初始值吗?
  • 我真的不知道。这就是我问的原因。
  • @Dilshan 要设置我通过 API 调用获得的初始值。这就是重点。
  • 我猜反应组件初始化较早。也许你应该只在渲染中使用 redux 值?

标签: javascript reactjs redux react-redux react-hooks


【解决方案1】:

而不是使用状态值。您可以直接在输入中使用 redux 值。它会为您填充初始值。不需要使用额外的状态。并且在redux中编写reducer函数并在onChange事件中调用它们

 <input
  id="impl-name"
  placeholder="gs-sentiment-analysis-impl-1"
  value={stepInfo.name} // ? using here
  onChange={(e) => {
    //Call redux reducer function for updating name;
    // enable the editing status to true for this step if any state changes
    setEditingStepStatus(1, true);
  }}
/>

【讨论】:

  • 你的意思是我应该在每次击键时发送一个 REDUX ACTION?这对性能来说是非常低效的。
  • 如果这是一个问题,您可以使用 onBlur 事件调度操作。希望这会起作用
  • 除非你在 reducer 中做一些非常愚蠢的事情或者每秒可以输入数十个字符,否则我怀疑 redux 会成为你应用程序的瓶颈。
  • @DrewReese 这个功能的 redux 状态非常大。由于它是一个步骤形式,有 8 个步骤,对于这么小的实现,更新 redux 状态确实效率低下。
  • @KaranKumar 然后不要使用 Redux。 redux.js.org/faq/general#when-should-i-use-redux
【解决方案2】:

好的,感谢Drew Reese,我能够理解手头的问题。

所以我想出了这个解决方案:

// local state
// setting up initial state
// =================================================================
const [name, setName] = React.useState(stepInfo.name);
const [description, setDescription] = React.useState(stepInfo.desc);

// workaround ?
React.useEffect(() => {
    setName(stepInfo.name);
    setDescription(stepInfo.desc);
}, [stepInfo.name, stepInfo.desc]);
// =================================================================

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 2022-01-14
    • 1970-01-01
    • 2021-09-22
    • 2018-03-09
    相关资源
    最近更新 更多