通过udemy教程并陷入困境,由于某种原因无法弄清楚什么是开心的。我查看了所有代码,据我所知,与教程相比,它看起来正确。代码:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container'));
searchbar.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)
}
onInputChange(e){
console.log(e.target.value)
this.setState({
term: e.target.value
})
}
onFormSubmit(e){
e.preventDefault()
}
render(){
return (
<form onSubmit ={this.onFormSubmit} className = "input-group">
< input
placeholder =" Get a forecast"
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){
return bindActionCreators({fetchWeather}, dispatch);
}
export default connect (null, mapDispatchToProps)(SearchBar);
减速器/ index.js
import axios from 'axios';
const API_KEY = 'c4c2ff174cb65bad330f7367cc2a36fa'
const ROOT_URL = `http://api.openweathermap.org/data/2.5/forecast?q=appid=${API_KEY}`;
export const FETCH_WEATHER = 'FETCH_WEATHER';
export function fetchWeather(city){
let url = `${ROOT_URL}&q=${city},us`;
let request = axios.get(url);
return {
type: FETCH_WEATHER,
payload: request
};
}
app.js
import React, { Component } from 'react';
import SearchBar from '../containers/search_bar';
export default class App extends Component {
render() {
return (
<div>
<SearchBar />
</div>
);
}
}
答案 0 :(得分:0)
回答,
您的代码有点混乱,actions/index.js
中的阻止是您的操作,应该位于searchbar
。如上所述,您要从import {fetchWeather} from '../actions/index';
组件中导入它:
FETCH_WEATHER
这里的reducer应该使用你在动作中设置的switch(action.type) {
case FETCH_WEATHER:
return [action.payload.data].concat(state);
}
return state;
类型来更新redux商店的状态,所以有以下几点:
combineReducers
然后直接导出或使用redux中的{{1}}来返回单个reducer函数(如果你有多个)。
链接到总是很棒的:this