英文:
data returns as undefined on first render
问题
function Story() {
let { id } = useParams();
const pin = useSelector(state => state.pins.pin);
const dispatch = useDispatch();
const userid = 2
useEffect(() => {
dispatch(getPin(id));
}, [dispatch, id]);
return (
<div className="container-fluid" >
<Upvote pin={pin.upvotes} userid={userid} />
</div>
);
}
function Upvote ({pin, userid}) {
///pin.filter(a => a.id === userid)
return <div>test<div/>
}
pin would be undefined at first render. I tried doing an if statement in Upvote. not sure if that is the right way
if(pin)
///filter
英文:
function Story() {
let { id } = useParams();
const pin = useSelector(state => state.pins.pin);
const dispatch = useDispatch();
const userid = 2
useEffect(() => {
dispatch(getPin(id));
}, [dispatch, id]);
return (
<div className="container-fluid" >
<Upvote pin={pin.upvotes} userid={userid} />
</div>
);
}
function Upvote ({pin, userid}) {
///pin.filter(a => a.id === userid)
return <div>test<div/>
}
pin would be undefined at first render. I tried doing an if statement in Upvote. not sure if that is the right way
if(pin)
///filter
答案1
得分: 3
这可能是因为pin
的初始状态未定义,或者pin
来自于一个异步操作,比如fetch。
你可以在只有当pin
已定义时有条件地渲染你的子Upvote
组件。
return (
<div className="container-fluid">
{pin && pin.upvotes && <Upvote pin={pin.upvotes} userid={userid} />}
</div>
);
英文:
That is probably because the initial state of pin
is undefined, or pin comes from a fetch operation, which is asynchronous.
What you can do is to conditionally render your child Upvote
component only if pin
is defined.
return (
<div className="container-fluid" >
{pin && pin.upvotes && <Upvote pin={pin.upvotes} userid={userid} />}
</div>
);
答案2
得分: 1
你可以这样做:
{pin && <Upvote pin={pin.upvotes} userid={userid} />}
只有在 pin 不是未定义时才渲染该组件。或者,当 pin 未定义时,你可能想要使用默认值,然后可以这样做:
<Upvote pin={pin ? pin.upvotes : defaultValue} userid={userid} />
英文:
You can do something like
{pin && <Upvote pin={pin.upvotes} userid={userid} />}
To only render the component when pin is not undefined. Alternatively you may want to have default values you can use when pin isn't defined and then you can do
<Upvote pin={pin ? pin.upvotes : defaultValue} userid={userid} />
答案3
得分: 0
在渲染 Upvote 之前,在 Story 中放置一个三元运算符,如果 pin
不存在,Upvote 就不会被渲染。
此外,当 pin
未定义时,它不会破坏你的代码。
英文:
Put a ternary operator in Story before rendering Upvote as if pin
is not present, Upvote won't render only.
Also, it will not break your code when pin
is undefined.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论