javascript - React 无法识别我的函数

标签 javascript

我正在使用 Redux 架构在 Reactjs 中开发一个应用程序。该应用程序使用第三方 API,当我将城市提交到搜索栏中时,该 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);

最佳答案

你需要导出redux组件,而不是react组件

导出默认连接(null, mapDispatchToProps)(SearchBar);

关于javascript - React 无法识别我的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45746851/

相关文章:

javascript - 使用 Chai 测试 HTML 元素的值

javascript - 与 onblur 一起使用的动态创建的元素和函数无法正常运行

javascript - 当我使用 JavaScript 更改类时,为什么 CSS 没有动画?

javascript - 覆盖 AngularJS 默认电子邮件验证器

javascript - 更改 CKEditor 中 "format"下拉菜单的大小

javascript - 什么时候 react 组件不是纯组件?

javascript - number 只能输入数字

javascript - 传递给 JavaScript 函数的参数数量是否需要与函数中定义的数量相同

javascript - 如何使 facebook 中的文本像按钮一样变白?

javascript - 使用 intro.js 在步骤中触发函数