React无法识别我的功能

时间:2017-08-18 00:41:33

标签: javascript

我正在利用Redux架构在Reactjs中开发一个应用程序。该应用程序正在使用第三方API,当我将一个城市提交到搜索栏时会被调用。在测试中,我收到一个控制台错误,内容如下:

Uncaught TypeError: this.props.fetchWeather is not a function

我不清楚为什么React告诉我fetchWeather在src / actions / index.js上作为函数存在时不是函数:

import axios from 'axios';

const API_KEY = 'spj3q-9huq]-hq -9hq 0rgjeth9e';
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?appid=${API_KEY}`;

export const FETCH_WEATHER = 'FETCH_WEATHER';

export function fetchWeather(city) {
  const url = `${ROOT_URL}&q=${city},us`;
  const request = axios.get(url);

  return {
    type: FETCH_WEATHER,
    // optional property
    // promise passed in
    payload: request
  };
}

this.props.fetchWeather(this.state.term);是我需要获取天气数据,这行代码存在于container / search_bar.js中:

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchWeather} from '../actions/index';

export default class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = {term: ''};

    this.onInputChange = this.onInputChange.bind(this);
    // always need to bind this
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

  onInputChange(event) {
    this.setState({term: event.target.value});
  }
  // callback
  onFormSubmit(event) {
    event.preventDefault();

    // We need to go fetch weather data
    this.props.fetchWeather(this.state.term);
    // clear out the search input
    this.setState({term:''});
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit} className="input-group">
        <input
          placeholder="Get a five day forecast in your favorite cities"
          className="form-control"
          value={this.state.term}
          onChange={this.onInputChange}
        />
        <span className="input-group-btn">
          <button type="submit" className="btn btn-secondary">Submit</button>
        </span>
      </form>
    )
  }
}

function mapDispatchToProps(dispatch) {
  // makes sure this flows down into the middleware
  return bindActionCreators({fetchWeather}, dispatch);
}

connect(null, mapDispatchToProps)(SearchBar);

1 个答案:

答案 0 :(得分:1)

您需要导出redux组件,而不是反应组件

export default connect(null, mapDispatchToProps)(SearchBar);

相关问题