尝试使用this.props.history.push,但this.props返回一个空对象

时间:2018-09-19 18:23:57

标签: javascript reactjs

var React = require('react')
var axios = require('axios')
var config = require('../../apiKeys')
var ReactRouter = require('react-router-dom')
var Router = ReactRouter.BrowserRouter;
var Route = ReactRouter.Route;
var Forecast = require('./Forecast');

class Header extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      city: null,
      weatherData: []
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
  };
  handleChange(e) {
    e.preventDefault();
    let input = e.target.value.split(' ,')[0];
    this.setState(function() {
      return {
        city: input
      }
    });
  };

  handleSubmit(e) {
    e.preventDefault();
    city = this.state.city

    function getCurrentWeather(city) {
      return axios.get("http://api.openweathermap.org/data/2.5/weather?q="+ city + `&type=accurate&APPID=${config.apiKey}`)
        .then(function(response) {
          return(response.data)
        })
      };

    function getFiveDayForecast(city) {
      return axios.get("http://api.openweathermap.org/data/2.5/forecast?q=" + city + `,us&mode=XML&APPID=${config.apiKey}&cnt=5`)
        .then(function(response) {
          return(response.data)
        })
      };
    axios.all([getCurrentWeather(city), getFiveDayForecast(city)])
      .then(axios.spread((currentWeatherResponse, fiveDayResponse) => {
        this.setState({ weatherData: [...this.state.weatherData, currentWeatherResponse] })
        this.setState({ weatherData: [...this.state.weatherData, fiveDayResponse]})
      }))
      .then(() => {
        this.props.history.push({
          pathname: '/forecast',
          search: `?forecast?city=${this.state.city}`,
          state: {
              data: this.state.weatherData}
        })
      });
    };

  render() {

    console.log(this.props.children)
    return(
      <Router>
        <div className="header-style">
          <p className="header-content-style"> Weather React App! </p>
          <div className="search-header">
            <form className="header-form" onSubmit={this.handleSubmit}>
              <input
                className="header-input-form"
                id="location"
                placeholder="City & State"
                type="text"
                autoComplete="off"
                onChange={this.handleChange}/>
              <button
                className="header-bar-button"
                type="submit"
                >
                Get Weather
              </button>
            </form>
          </div>
        </div>
      </Router>
    )
  }
}


module.exports = Header



var React = require('react')
var ReactDOM = require('react-dom')
require('./index.css')
var Home = require('./component/Home')
var ReactRouter = require('react-router-dom')
var Router = ReactRouter.BrowserRouter;
var Route = ReactRouter.Route;
var Link = ReactRouter.Link
var Forecast = require('./component/Forecast')
var Interval = require('./component/Interval')

class App extends React.Component {
  render() {
    return (
      <Router>
        <div>
          <Route exact path="/" component = {Home} />
          <Route path="/forecast" component={Forecast} />
          <Route path="/detail/:interval" component = {Interval} />
        </div>
      </ Router>
    )
  }
};


ReactDOM.render(
  <App />,
  document.getElementById("app")
);

我有一个标头组件,该组件具有用于按城市和州搜索的表单。形式onSubmit触发一个事件函数,该事件函数具有用于api调用的两个函数声明和一个包装在axios.all中的api调用的函数调用。然后将响应设置为我的this.state,然后具有this.props.history.push函数以呈现新组件和路由。在console.log上,我的this.props是一个空对象,我无法在未定义的名称上调用.history.push。

当我在另一个实际上具有this.props.history的组件中完成了一些类似的操作时,我试图弄清楚为什么在此特定组件中this.props为空。顶部的代码来自我的Header Component,底部的是我的index.js文件

请看看。

1 个答案:

答案 0 :(得分:0)

要在您的history中获得props,您需要component wrappedwithRouter

module.exports = withRouter(Header);

withRouter负责查找Router,并将所有相关的道具传递给您的组件。