我正在使用电子反应样板,反应钩子和上下文来研究对象。
我在react-router-dom上有问题。在'/'后面定义的每个路径,导航都行不通,否则它将正常工作。
我尝试在上面添加确切的属性,但是首页停止了渲染
这是我的代码:
Index.js:
import React, { Fragment } from 'react';
import { render } from 'react-dom';
import './app.global.css';
import App from './App';
render(<App />, document.getElementById('root'));
App.js:
import React, { useState } from 'react';
import { hot } from 'react-hot-loader';
import PruebaContext from './pruebas/Context';
import Navigator from './Routes'
function App() {
const Hola = 'hola';
const [monja, setMonja] = useState();
const setMonjaFunc = monjaData => {
setMonja(monjaData);
};
return (
<PruebaContext.Provider value={{ Hola, monja, setMonjaFunc }}>
<Navigator />
</PruebaContext.Provider>
);
}
export default hot(module)(App);
这是Routes.js上的问题:
import React from 'react'
import {Router, Route, Switch, } from 'react-router-dom';
import history from './pruebas/History';
import Second from './components/Second';
import Home from './components/Home';
import Third from './components/Third'
const Navigator = () => {
return(
<Router history={history}>
<Switch>
<Route path='/Second' component={Second}/>
<Route path='/Third' component={Third} />
<Route path='/' component={Home}/>
</Switch>
</Router>
)
}
export default Navigator;
和Home.js:
import React, { useEffect, useContext } from 'react';
import styles from './Home.css';
import PruebaContext from '../pruebas/Context';
import { Link, useHistory } from 'react-router-dom';
import Counter from './Counter';
const Home = () => {
const Context = useContext(PruebaContext);
const history = useHistory();
useEffect(() => {
console.log(Context.Hola);
Context.setMonjaFunc('adios');
}, []);
const DoSomething = () => {
console.log('do');
Context.setMonjaFunc('1');
};
const DoSomethingTwo = () => {
console.log('2');
Context.setMonjaFunc('2');
};
//NAVIGATION 1ST TRY
const Nav = () => {
history.push('/Third')
}
return (
<div className={styles.container} data-tid="container">
<button type="button" onClick={DoSomethingTwo}>2Bum</button>
<button type="button" onClick={DoSomething}>bum</button>
<button type="button" onClick={Nav}> n</button>
<h2>Home</h2>
<h2>{Context.Hola}</h2>
<h2>{Context.monja}</h2>
{/* NAVIGATION 2ND TRY */}
<Link to='/Second' >Go to second</Link>
</div>
);
};
export default Home;