簡體   English   中英

React useState 沒有選擇初始狀態?

[英]React useState is not picking initial state?

我需要一個表單值來預填充來自 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 值。它會為您填充初始值。 無需使用額外的狀態。並在 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);
  }}
/>

好的,感謝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]);
// =================================================================

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM