【问题标题】:ReactJS Custom Hook not rendering the expected outputReactJS Custom Hook 没有呈现预期的输出
【发布时间】:2020-12-08 13:37:15
【问题描述】:

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

我希望在屏幕上看到:'标签:',但它是“标签:”,因此该选项未定义!

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

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

【问题讨论】:

    标签: javascript reactjs react-hooks use-state


    【解决方案1】:

    仅仅因为它们使用相同的自定义钩子,它们不会自动共享状态。每次运行 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多