将 props 参数传递到 State 变量中

huangapple go评论72阅读模式
英文:

React pass props parameters into State variable

问题

我看到了很多关于这个问题的问题和答案,但我仍然不能弄清楚用react 18实现这一点的正确方法是什么。

将参数通过props传递到子组件以在状态参数中使用的正确方法是什么?

我的当前代码看起来像这样 - 但似乎是错误的 - 当我需要它时,数据不在那里:

const ChildComp = (props) => {
   const [selectedTenant, setSelectedTenant] = useState(null);
   const [scheduleID, setScheduleID] = useState(0);

   useEffect(() => {
        if (props.scheduleID && props.scheduleID > 0) {
            setScheduleID(props.scheduleID);      
            setSelectedTenant(props.selectedSchedule.TenantID);
        } else {
             // 如果scheduleID未传递,则执行一些其他代码
        }
    }, [])
}

是否有更好的方法来初始化状态参数?
我稍后在JSX代码中使用它们,看起来它们保持着null/0值,只有在渲染后才运行useEffect代码。
用户将能够更改租户ID(使用react-select),因此需要状态...

英文:

I've seen many questions and answers about this issue, but I still can't figure out what is the right way to achieve this with react 18

What is the right way to send parameter via props into a child component to be used in a state parameter ?

my current code looks like this - but it seems wrong - the data is not there when I need it:

const ChildComp = (props) => {
   const [selectedTenant, setSelectedTenant] = useState(null);
   const [scheduleID, setScheduleID] = useState(0);

   useEffect(()=>{
        if(props.scheduleID && props.scheduleID > 0)
        {
            setScheduleID(props.scheduleID);      
            setSelectedTenant(props.selectedSchedule.TenantID);
        } else
        {        
             // some other code in case scheduleID is not passed
        }
    },[])

}

Is there a better way to initialize the state parameters ?
I use them later in the JSX code and looks like they keep the null/0 values and only after being rendered the useEffect code runs.
The user will be able to change the tenant id (using react-select) hence the state is needed...

答案1

得分: 1

}, [props.scheduleID, props.selectedSchedule.TenantID])
英文:

pass relevant props to useEffect dependency array

},[props.scheduleID, props.selectedSchedule.TenantID])

答案2

得分: 0

在你的情况下,最佳实践是使用这种方法:
避免使用状态并有条件地调用props
例如:

{props.scheduleID || {otherValue}}

{props.scheduleID > 0 ? {props.scheduleID} : {OtherValue}}

或者你可以将整个逻辑放入一个方法中并使用它:

const showValue = (prop, alternative) => prop > 0 ? prop : alternative

{showValue(props.scheduleID, 'otherValue')}
英文:

The best practice in your case is using this method:
Avoid using states and call the props conditionally
Ex:

{props.scheduleID || {otherValue} }

{props.scheduleID > 0 ? {props.scheduleID} : {OtherValue }

Or you can put the whole logic in a method and use it:

const showValue = (prop, alternative) => prop > 0? prop : alternative

{showValue(props.scheduleID, 'otherValue')}

huangapple
  • 本文由 发表于 2023年1月9日 15:40:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054319.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定