React Hooks和商店管理

时间:2020-05-05 18:56:30

标签: reactjs react-hooks

我正在转换具有功能组件和redux的旧应用程序以使用react钩子,并且在学习它的同时,看来我真的不再需要使用redux吗?

最初,我会存储一个数据,例如配方和一些化简器,例如ADD_INGREDIENT,这更多用于调试,并且其中一个挂钩也是useReducer。

因此,在这种情况下,如果我在配方中添加成分,然后转到具有可以访问混合器上下文的另一个组件的页面,那么这是否与在redux中拥有全局存储区相同?

在Redux或Mobx中,我该怎么办?

import React, { createContext, useContext, useState } from 'react';
import { Route, Link, BrowserRouter } from "react-router-dom";

const MixerContext = createContext()

const MixerProvider = ({ children }) => {
  const [ingredients, setIngredients] = useState([
    'Tequila',
    'Vodka',
    'Lime',
    'Egg Whites',
    'Cilantro'
  ])

  const [recipe, setRecipe] = useState([])
  const addToRecipe = ingredient => {
    if (!recipe.find(r => r === ingredient)) setRecipe([...recipe, ingredient])
  }

  return (
    <MixerContext.Provider
      value={{
        ingredients,
        setIngredients,
        recipe,
        setRecipe,
        addToRecipe
      }}
    >
      {children}
    </MixerContext.Provider>
  )
}

const Ingredients = props => {
  const { addToRecipe, ingredients } = props
  return (
    <div style={{ border: 'solid 1px #000', padding: '25px' }}>
      <h1 style={{ marginTop: 0 }}>Ingredients</h1>
      {ingredients.map((ingredient, index) => (
        <li key={index}>
          <a href="#" onClick={() => addToRecipe(ingredient)}>{ingredient}</a>
        </li>
      ))}
    </div>
  )
}

const Recipe = props => {
  const { recipe } = props
  return (
    <div style={{ border: 'solid 1px #000', padding: '25px' }}>
      <h1 style={{ marginTop: 0 }}>Recipes</h1>
      {recipe.map((r, idx) => <li key={idx}>{r}</li>)}
    </div>
  )
}

const JustRecipes = () => {
  const contextFromMixer = useContext(MixerContext)
  const { recipe } = contextFromMixer

  return (
    <div style={{ border: 'solid 1px #000', padding: '25px' }}>
      <h1>Recipe Page</h1>
      <Recipe recipe={recipe} />
    </div>
  )
}

const Main = () => {
  const contextFromMixer = useContext(MixerContext)
  const { ingredients, recipe, addToRecipe } = contextFromMixer

  return (
    <>
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <Ingredients addToRecipe={addToRecipe} ingredients={ingredients} />
        <Recipe recipe={recipe} />
      </div>
      <Link to="/recipes">Recipes</Link>
    </>
  )
}

const App = () => {
  return (
    <BrowserRouter>
      <MixerProvider>
        <Route exact path="/" component={Main}/>
        <Route path="/recipes" component={JustRecipes}/>
      </MixerProvider>
    </BrowserRouter>
  );
}

export default App;

0 个答案:

没有答案