I just wonder, if is it possible to render a ponent inside a useEffect hook. I have two ponents, let's say A and B. In Component A, I have my useEffect hook as follows. While testing some condition inside hook, I want to render a ponent B.
export default function A() {
const [location, setlocation] = usestate(null);
useEffect(() => {
if (condition) {
<B />; // it does not render anything though
} else {
//code
}
}, [location]);
}
export default function B() {
const test = () => {
console.log("testing");
};
return (
<View style={styles.container}>
<Button title={"Click Me"} onPress={test} />
</View>
);
}
I just wonder, if is it possible to render a ponent inside a useEffect hook. I have two ponents, let's say A and B. In Component A, I have my useEffect hook as follows. While testing some condition inside hook, I want to render a ponent B.
export default function A() {
const [location, setlocation] = usestate(null);
useEffect(() => {
if (condition) {
<B />; // it does not render anything though
} else {
//code
}
}, [location]);
}
export default function B() {
const test = () => {
console.log("testing");
};
return (
<View style={styles.container}>
<Button title={"Click Me"} onPress={test} />
</View>
);
}
Share
Improve this question
edited Aug 2, 2021 at 12:16
AKX
170k16 gold badges142 silver badges218 bronze badges
asked Aug 2, 2021 at 12:14
MeanaMeana
252 silver badges13 bronze badges
3
- 4 I dont think so , but you can update a state and conditionally render the ponent – brk Commented Aug 2, 2021 at 12:16
- You have to conditionally return the <B/> after your useEffect hook. – Shubham J. Commented Aug 2, 2021 at 12:17
- Functional ponents render their return value. Anything not in the return value won't be rendered. – Dave Newton Commented Aug 2, 2021 at 12:26
1 Answer
Reset to default 6That's not where you'd want to use useEffect
anyway.
Since location
is a state atom, it changing will cause a rerender, so the effect hook is unnecessary for that. (I assume // code
is more plicated than what you let on here, though...)
For the equivalent, but working example,
export default function A() {
const [location, setlocation] = useState(null);
if (condition) {
return <B />;
}
// code
return null;
}
EDIT based on ments
To force a rerender (unmount + remount) of a ponent, you can use an arbitrary key for it:
export default function A() {
const [location, setlocation] = useState(null);
React.useEffect(() => {
// ....
}, [location]);
return <B key={location} />;
}
To force it to rerender based on a condition in an effect,
export default function A() {
const [location, setlocation] = useState(null);
const [conditionCounter, setConditionCounter] = useState(0);
React.useEffect(() => {
if(condition) {
setConditionCounter(c => c + 1);
}
}, [location]);
return <B key={conditionCounter} />;
}
(or maybe just new Date()
or Math.random()
, but a counter works.)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744326182a4568658.html
评论列表(0条)