我正在使用 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/