开发者问题收集

useEffect() 完成后 setState 并具有值

2020-10-15
106
const initData = {
    name: "",
    class: ""
}
const [currentStudent, setCurrentStudent] = useState({});

useEffect(() => {
    // My example code to setState
    setCurrentStudent(exampleData)
    //The result of currentStudent is {name: "Alex", class: "4"}
}, []);
     
const [formData, setFormData] = useState({ condition ? currentStudent : initData });

这意味着如果 formData 为真,则结果是 currentStudent {name: "Alex", class: "4"> ,如果为假,则结果为 initData 状态。

但是当我尝试上面的代码时,结果是一个像这样的空对象 {}.

我怎样才能设置 formData state = currentStudent ({name: "Alex", class: "4"})

3个回答

我要更改代码。

const initData = {
  name: "",
  class: ""
}
const [currentStudent, setCurrentStudent] = useState({});
const [formData, setFormData] =useState({});
useEffect(() => {
  setCurrentStudent(exampleData)   // My example code to setState
                                  //The result of currentStudent is {name: "Alex", class: "4"}
  setFormData(condition ? exampleData: initData);
}, []);
A.R.SEIF
2020-10-15

请尝试这个。

const initData = {
  name: "",
  class: ""
}
const [currentStudent, setCurrentStudent] = useState({});
const [formData, setFormData] =useState({});
useEffect(() => {
  setCurrentStudent(exampleData)
  setFormData(condition ? exampleData: initData);
}, [condition]); // or use props variable which is used for condition value.

它的目的是当 props 改变时更新功能组件。 由于条件大多是从 props 设置的,因此需要在 userEffect 中将 props 或条件设置为参数,如 componentWillReceiveProps

Everest Climber
2020-10-15

第一次组件渲染时,将应用初始化值状态。此后您已设置当前用户。它将不会被应用。为什么不在 setState 的 init 中设置:

const [currentStudent, setCurrentStudent] = useState(exampleData);

或者您可以设置它 useEffect 函数:

setFormData(condition ? exampleData : initData);
Viet Dinh
2020-10-15