Я конвертирую старое приложение с функциональными компонентами и redux, чтобы использовать перехватчики реакции, и, изучая его, мне кажется, что мне больше не нужно использовать 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;