我正在制作简单的天气应用程序,我的最后一部分是工作,我无法在没有重新加载页面的情况下进行路由路由,当我点击显示我想更改网址的显示具体天气的按钮时,该路由就可以工作星期几的名字,这就是我的路线在index.js中的样子
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { Router, Route, Switch } from "react-router-dom";
import WeatherByDays from './components/WeatherByDays';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<Router>
<div>
<Switch>
<Route path="/" component={App} />
<Route path="/:day" exact component={<WeatherByDays />} />
</Switch>
</div>
</Router>,
document.getElementById('root')
);
这是一个有关天气的绘图信息的组件
import moment from 'moment';
import { withRouter } from 'react-router-dom';
import '../component-styles/weatherByDays.css';
class WeatherByDays extends React.Component {
state = {
data: [],
closeButton: false
};
static getDerivedStateFromProps(props) {
const arr = props.data.filter(e => {
return moment(e.dt * 1000).format('dddd') === props.day;
});
return { data: arr };
};
render() {
console.log(this.props.match)
const weather = this.state.data.map((e, i) => {
return <h3 key={i}>{Math.floor(e.main.feels_like)}</h3>
});
return (
<div className='weather-main'>
<h1>{this.props.day}</h1>
{weather}
<button onClick={this.props.close}>X</button>
</div>
);
};
};
export default WeatherByDays;
答案 0 :(得分:1)
我认为这句话是错误的<Route path="/:day" exact component={<WeatherByDays />} />
一定是这样的<Route path="/:day" exact component={WeatherByDays} />
您的switch语句不正确,必须将精确的prop放在“ /”路径上,这样才能浏览其他路径。
<Switch>
<Route path="/" exact component={App} />
<Route path="/:day" component={WeatherByDays} />
</Switch>