Estoy usando contexto y API reductora para la lógica y la gestión del estado. El siguiente código devuelve el proveedor de contexto, que se llama en App.js. ¿Por qué no se renderiza el componente?
SingerState.js
import React, { useReducer } from "react"; import SingerContext from "./singerContext"; import SingerReducer from "./singerReducer"; import { GET_SINGER, SET_LOADING } from "../types"; const SingerState = (props) => { console.log('foo') const initialState = { name: null, songs: null, loading: false, }; const [state, dispatch] = useReducer(SingerReducer, initialState); const getSinger = () => { dispatch({ type: GET_SINGER, payload: { name: "jb", songs: ["song1", "song2"], }, }); }; const setLoading = () => { dispatch({ type: SET_LOADING, }); }; return ( <SingerContext.Provider value={{ name: state.name, songs: state.songs, loading: state.loading, getSinger, setLoading, }} > {props.childer} </SingerContext.Provider> ); }; export default SingerState;El código completo está aquí: https://codesandbox.io/s/heuristic-shockley-9u2xb?file=/src/App.js:0-411
Aplicación.js
import "./App.css"; // import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import SingerState from "./context/singer/singerState"; import Navbar from "./components/Navbar"; import Singer from "./components/singer/Singer"; export default function App() { return ( <div className='App'> <Navbar /> <SingerState> <Singer /> </SingerState> </div> ); }cantanteReductor.js
import { GET_SINGER, SET_LOADING } from "../types"; const reducer = (state, action) => { switch (action.types) { case GET_SINGER: return { ...state, name: action.payload.name, song: action.payload.song, loading: false, }; case SET_LOADING: return { ...state, loading: true, }; default: return state; } }; export default reducer;cantanteContexto.js
import { createContext } from "react"; const singerContext = createContext(); export default singerContext;Debería ser {props.children} no {props.childer} en SingerState.js . Hice esta corrección dentro de su Sandbox y está funcionando. Para asegurarme, cambié initialState a esto:
const initialState = { name: "It's me", songs: null, loading: false, };Tiene 2 errores tipográficos en su código: 1- Debería ser {props.children} no {props.childer} en SingerState.js. (Gracias a yousomar)
Y en SingerReducer.js. En vez de :
switch (action.types) { case GET_SINGER: use action.type porque los types no están definidos
¡¡¡Cuidado con los errores tipográficos!!!