ReactJS Custom Hook 没有呈现预期的输出

ReactJS Custom Hook not rendering the expected output

我正在尝试使用 ReactJS 自定义 Hooks,但我不明白下面的示例中发生了什么!

我希望在屏幕上看到:'Label: <followed by one of the selected option ("Bananas" or "Apples" or "Oranges")>',但它是 'Label: ',所以选项未定义!

谁能给我解释一下幕后发生的事情,为什么我看不到该选项的预期输出?

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 />
    </>
  );
}

只是因为它们使用相同的自定义钩子,所以它们不会自动共享状态。每次你 运行 useFruits 你都会创建一个新的隔离状态,它只能在那个实例中访问。每当创建状态时,它默认为未定义。

要解决您的问题,您需要将组件包装在上下文中,并将状态放在上下文中。像这样:

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)

别忘了包装你的组件:

<FruitProvider>
      <FruitDropdown />
      <FruitLabel />
</FruitProvider>