REACT-REDUXのACTIONSから関数をディスパッチする際に問題があります。 'mapDispatchToProps' でアクションクリエータを呼び出すためにコンテナ内でmapDispatchToPropsを正しく使用/バインドする方法
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)という名前の 'コンテナ' を持っている:
私は以下の 'アクション'(アクション/ index.js)を持っています以下のように記述されています:
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はすなわち、コンソールconsole.log("Request in Actions: ", request);
にwittingないファイルの操作/ index.jsからfetchWeatherアクションを発射されていません。
注: 最新のmapDistpatchToPropsのみを使用する必要がありました。これも働いていますreturn bindActionCreators({fetchWeather}, dispatch);
しかし、古いものを探していません。
お願いします。
がthis.props.fetchWeather(city)
が
dispatch(fetchWeather(city))
にマッピングされていることを意味
const mapDispatchToProps = (dispatch) => {
return {
fetchWeather: (city) => dispatch(fetchWeather(city))
};
};
(あなたのコードはfetchWeather
一部をミス:ありがとう
お返事ありがとうございます。 "Uncaught TypeError :(0、_index2.default)は関数ではありません" – Owais
@Owais申し訳ありません:1 - 私は私の答えを間違って入力しました。余分な中括弧があります。これは、 'const mapDispatchToProps =(ディスパッチ)=> {return {fetchWeather:(city)=>ディスパッチ(fetchWeather(city))}; }; '2 - インポートに問題があります。デフォルトで' fetchWeather'をエクスポートしないので、 '../ actions/index ';'(中括弧)から 'import {fetchWeather}'を実行する必要があります。それを反映する答えを編集しました。 – MDH
ありがとうございます。それは働いている。私は受け入れてupvoted。ありがとう – Owais