我在REACT-REDUX中的動作中調度函數時遇到問題。如何在容器中正確使用/綁定mapDispatchToProps以調用動作創建者
我在下面的 '行動'(動作/ index.js):
import axios from 'axios';
const API_KEY = 'sdfmbsjfsdf78fsdf78s78fs87f7s2bc5';
const ROOT_URL = `http://api.example.org/data/2.5/weather?appid=${API_KEY}`;
export const FETCH_WEATHER = 'FETCH_WEATHER';
export function fetchWeather(city){
const url = `${ROOT_URL}&q=${city},pk`;
const request = axios.get(url);
console.log("Request in Actions: ", request); // this line is not showing in console because DISPATCHED action is not coming here
return {
type: FETCH_WEATHER,
payload: request
};
}
而且,我有一個 '容器' 命名爲 '搜索欄'(集裝箱/ SearchBar.js),其中 'mapDispatchToProps'已經被寫爲:
import React from 'react';
import { connect } from 'react-redux';
import fetchWeather from '../actions/index';
class SearchBar extends React.Component{
constructor(props){
super(props);
this.state = { term: '' };
}
onInputChange(event){
this.setState({ term: event.target.value });
}
onFormSubmit(event){
event.preventDefault();
this.props.fetchWeather(this.state.term);
this.setState({ term: ''});
}
render(){
return(
<form onSubmit={ this.onFormSubmit.bind(this) } className="input-group">
<input
className="form-control"
placeholder="Search your favourite cities to get a five-day forecast"
value={ this.state.term }
onChange={ this.onInputChange.bind(this) }
/>
<span className="input-group-btn">
<button type="submit" className="btn btn-secondary">Search</button>
</span>
</form>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchWeather: (city) => {
dispatch({
type: "FETCH_WEATHER"
});
}
};
};
export default connect(null, mapDispatchToProps)(SearchBar);
問題:
我的問題是:無論何時,我寫在搜索一些文本BAR並點擊SearchBar.js的搜索按鈕,mapDispatchToProps未擊發動作/ index.js的fetchWeather操作文件,即不知曉到控制檯console.log("Request in Actions: ", request);
。
注意: 我只需要使用最新的mapDistpatchToProps。這也是工作return bindActionCreators({fetchWeather}, dispatch);
但不尋找老東西。
請幫忙。由於
感謝您的回覆。這樣的映射給出了這樣的錯誤:「Uncaught TypeError:(0,_index2.default)不是一個函數」 – Owais
@Owais對不起:1 - 我打錯了我的答案,還有一個額外的大括號,應該是:'const mapDispatchToProps =(派遣)=> {return {fetchWeather:(city)=> dispatch(fetchWeather(city))}; };'2 - 導入有問題,您應該從'../ actions/index';'(花括號)導入{fetchWeather},因爲您不會將'fetchWeather'導出爲默認值。我編輯了答案來反映這一點。 – MDH
非常感謝。這是工作。我接受並贊成。謝謝 – Owais