如何根据React父组件传入的props值将effective_date_status设为true或false
实现方案
方案1:useEffect监听props变化(子组件需要独立修改状态时使用)
如果子组件后续需要自行修改effective_date_status的值,保留本地state的前提下,监听父组件传入的props变化同步更新state即可:
import React from 'react' const 你的子组件名 = (props) => { const [effective_date_status, setEffectiveDateStatus] = React.useState(false) // 这里假设父组件传入的props字段名为dateStatus,替换成你实际的props字段名即可 React.useEffect(() => { setEffectiveDateStatus(props.dateStatus === 1) }, [props.dateStatus]) // 组件其余逻辑... }
判断逻辑props.dateStatus === 1天然符合需求:props传1时返回true,传0时返回false。如果要兼容异常值可以加兜底逻辑,比如写成setEffectiveDateStatus(Number(props.dateStatus) === 1)。
方案2:直接派生状态(子组件不需要独立修改状态时使用)
如果effective_date_status完全由父组件props决定,子组件不会自行修改这个值,可以直接省略本地state定义,性能更优也不需要维护同步逻辑:
const 你的子组件名 = (props) => { // 直接根据props计算得到状态值,不需要额外声明state const effective_date_status = props.dateStatus === 1 // 组件其余逻辑... }
内容的提问来源于stack exchange,提问作者Karthick M
相关产品推荐
相关产品推荐

