[英]ReactJS Custom Hook not rendering the expected output
I am experimenting with ReactJS custom Hooks, but I don't understand what's happening in the example below!我正在试验 ReactJS 自定义 Hooks,但我不明白下面的示例中发生了什么!
I expect to see on the screen: 'Label: <followed by one of the selected option ("Bananas" or "Apples" or "Oranges")>', but it is 'Label: ' so the optionis undefined!我希望在屏幕上看到:'标签:<后跟所选选项之一(“香蕉”或“苹果”或“橙子”)>',但它是'标签:'所以选项未定义!
Could someone explain me what's happening under the hood, why I cannot see the expected output for the option?有人可以解释一下幕后发生了什么,为什么我看不到该选项的预期 output 吗?
const useFruit = () => {
const [option, setOption] = useState<string>();
const [options] = useState(["Bananas", "Apples", "Oranges"]);
return {
option,
setOption,
options,
};
};
const FruitDropdown = () => {
const { options, setOption } = useFruit();
return (
<select
placeholder="Select option"
onChange={(e) => {
setOption(e.target.value);
}}
>
{options.map((option) => (
<option value={option}>{option}</option>
))}
</select>
);
};
const FruitLabel = () => {
const { option } = useFruit();
return (
<label>Label: {option}</label>
);
};
export default function play() {
return (
<>
<FruitDropdown />
<FruitLabel />
</>
);
}
Just because they are using the same custom hook, they are not automatically sharing state.仅仅因为它们使用相同的自定义钩子,它们不会自动共享 state。 Every time you run useFruits you will create a new isolated state which is only accessable in that instance how the hook.
每次运行 useFruits 时,您将创建一个新的隔离 state ,它只能在该实例中如何访问。 And whenever a the state is created it defaults to undefined.
并且每当创建 state 时,它默认为未定义。
What you need in order to solve your problem is to wrap your components inside a context and place the state inside the context.为了解决您的问题,您需要将组件包装在上下文中并将 state 放置在上下文中。 Something like this:
像这样的东西:
const FruitContext = createContext()
const FruitProvider = ({ children }) => {
const [option, setOption] = useState<string>();
const [options] = useState(["Bananas", "Apples", "Oranges"]);
return (
<FruitContext.Provider value={{ option, setOption, options }}>{children}</FruitContext.Provider>
)
}
export const useFruits = () => useContext(FruitContext)
Dont forget to wrap your components:不要忘记包装你的组件:
<FruitProvider>
<FruitDropdown />
<FruitLabel />
</FruitProvider>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.