[英]How to update props correctly in React functional component
我是新手,想问一下这段代码是否是好的做法,因为我觉得我做错了什么,但不确定是什么。
我有一个主要的 class 组件,它有一个由宽度、高度等组成的封装阵列。
我将这个包数组作为道具传递给另一个我想更新这些值的功能组件。 目前我的实现如下所示:
<Card pck={pck} key={pck.packageId}/>
export default function Card(props) {
const widthProperties = useState(0);
props.pck.width = widthProperties[0]
const setWidth = widthProperties[1];
<input type="number" id={props.pck.packageId} className="form-control"
value={props.pck.width}
onChange={(e) => setWidth(parseInt(e.target.value))}
placeholder="Width" required/>
}
它工作正常,但正如我所说,我相信我没有正确使用带有props
的useState
。 有人可以解释这里有什么问题吗? 因为更新 props 的 state 的 3 行代码对我来说看起来很奇怪。
你永远不会像这里那样直接改变道具: props.pck.width = widthProperties[0]
。
为了有正确的数据流, width
和setWidth
应该在父组件中并传递给子组件,以便子组件可以通过调用setWidth
来更新它们的width
。
因此,由于父组件是 class 组件,您将拥有如下内容:
class CardsList extends Component {
state = {
packages: []
}
componentDidMount() {
fetch('api.com/packages')
.then(response => response.json())
.then(result => this.setState({ packages: result.items }))
}
setWidth = (width, packageId) => {
this.setState({
packages: this.state.packages.map(
pck => pck.packageId === packageId ? { ...pck, width } : pck
)
})
}
render() {
return (
<div className="cards-list">
{this.state.packages.map(pck => (
<Card pck={pck} setWidth={this.setWidth} key={pck.packageId}/>
))}
</div>
)
}
}
还有一个 Card 组件,例如:
const Card = ({ pck, setWidth }) => (
<input value={pck.width} onChange={e => setWidth(e.target.value, pck.packageId)} />
)
从 useState 解构值和设置器 function 是很常见的,如下所示:
[value, setValue] = useState(initialValue);
根据我从您的问题中收集到的信息, props.pck.width 是输入的初始值,因此您可以执行以下操作:
[width, setWidth] = useState(props.pck.width);
<input type="number" id={props.pck.packageId} className="form-control"
value={width}
onChange={(e) => setWidth(parseInt(e.target.value))}
placeholder="Width" required/>
您不会那样使用useState
。 useState
返回一个包含两个东西的数组:
因此,在您的情况下,它应该如下所示:
const [widthProperties, setWidthProperties] = useState({}); //Here you can either pass an empty object as an initial value or any structutre you would like.
setWidthProperties(props.pck.width); //Or whatever you want to set it to.
请记住永远不要手动更改变量。 只能通过 function useState
为您提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.