我正在使用React钩子,并尝试使用向下传递的props
设置组件内部常量的初始状态。我见过多个examples of this online,但是当我这样做时,数组解构将返回整个props
对象,而不是我想要的实例。
Import React, {useState} from "react";
const MyComponent = (props) => {
console.log(props) // {date: "2019-11-26", task: "cooking"}
const [date, setDate] = useState(props);
console.log(date) // {date: "2019-11-26, task: "cooking"}
return (...)
}
export default MyComponent;
我假设对象/数组解构后,date
的值将自动被分配props
(字符串"2019-11-26"
)中的值,而不是整个{{1} }对象。我想念什么?我可以通过设置props
来解决这个问题,但这会破坏eslectts react插件destructuring rule的作用,我想避免这种情况。
修改
感谢helloitsjoe为answer解决了我的问题!
答案 0 :(得分:1)
您可以在参数定义中分解道具。请注意,最好的做法是从道具设置状态以将道具initialX
或defaultX
命名为状态,并应从该点开始使用该状态。>
const MyComponent = ({ initialDate }) => {
const [date, setDate] = useState(initialDate);
...
}
答案 1 :(得分:1)
您需要像这样破坏props
的结构:
const MyComponent = ({date, task}) => {
const [myDate, setMyDate] = useState(date);
console.log(myDate); //get the date here
}
答案 2 :(得分:0)
您可以这样做:
Import React, {useState} from "react";
const MyComponent = (props) => {
const {date} = props //destructing
console.log(props) // {date: "2019-11-26", task: "cooking"}
const [date, setDate] = useState(date);
console.log(date)
return (...)
}
export default MyComponent;
OR
Import React, {useState} from "react";
const MyComponent = ({date}) => { //destructing
const [date, setDate] = useState(date);
console.log(date)
return (...)
}
export default MyComponent;
答案 3 :(得分:0)
您必须破坏道具才能使破坏真正起作用。
尝试
const MyComponent = ({date, task}) => {
....
}
答案 4 :(得分:0)
如果日期属性在对象内,您应该遵循以下方法:
import "./styles.css";
import React, { useState } from "react";
const basket = {
apples: 10,
banana: 5
};
const SimpleComp = () => {
const [{ apples, banana }, setBasket] = useState({ ...basket });
return (
<div>
<button
onClick={() =>
setBasket((currentState) => ({
...currentState,
apples: currentState.apples + 1,
banana: currentState.banana + 1
}))
}
>
Add Fruit
</button>
<div> Apples : {apples} </div>
<div> Banana : {banana} </div>
</div>
);
};
export default SimpleComp;
向 useState 提供了一个篮子的副本,因此尊重不变性,自己尝试code Sandbox
或者在简单日期变量的情况下:
import "./styles.css";
import React, { useState } from "react";
const actualDate = new Date()
const actualDateToday = actualDate.getDate()
console.log(actualDateToday);
const MyComponent = () => {
console.log(actualDate) // {date: "2019-11-26", task: "cooking"}
const [date, setDate] = useState(actualDateToday);
console.log(date) // {date: "2019-11-26, task: "cooking"}
return (
<div>
<p> Date Today: {actualDateToday} </p>
<button
onClick={() => setDate(date => date + 1)} >
Add a day
</button>
<p> Date Tomorrow: {date}</p>
</div>
);
}
export default MyComponent
试试这里code Sandbox