我正在尝试将PixaBay克隆应用程序重新配置为Redux。应用程序将searchText状态设置为输入的值,然后在用户键入搜索文本时触发Axios GET请求回调,然后检索图像。
我在我的reducer上收到解析错误,但是由于我认为代码正确,所以我不理解该错误。有人可以帮我解决问题吗?谢谢!
容器
import React, { Component } from 'react';
import { fetchPhotos } from '../actions/actions';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import TextField from 'material-ui/TextField';
import ImageResults from '../imageResults/ImageResults';
class Search extends Component {
FetchPhotosHandler = (e) => {
this.props.fetchPhotos(e);
}
render() {
console.log(this.props.images);
return (
<div>
<TextField
name="searchText"
value={this.props.searchText}
onChange={this.FetchPhotosHandler}
floatingLabelText="Search for photos"
fullWidth={true} />
<br />
{this.props.images.length > 0 ? (<ImageResults images={this.props.images} />) : null}
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchPhotos, dispatch});
}
export default connect(null, mapDispatchToProps)(Search);
动作
import axios from 'axios';
export const FETCH_PHOTOS = 'FETCH_PHOTOS';
const ROOT_URL = 'https://pixabay.com/api';
const API_KEY = 'my_api_key';
const searchText = '';
export function fetchPhotos(e) {
const url = `${ROOT_URL}/?key=${API_KEY}&q=${searchText}&image_type=photo`;
const request = this.setState({searchText: e.target.value}, () => {
axios.get(url)
.then(response => {
this.setState({images: response.data.hits});
})
.catch(error => {
console.log(error)
});
});
return {
type: FETCH_PHOTOS,
payload: request
};
}
减速器
import { FETCH_PHOTOS } from '../actions/actions';
const initialState = {
searchText: '',
images: []
}
const reducer = (state = initialState, action) => {
switch(action.type) {
case FETCH_PHOTOS:
return {
...state,
action.data.hits
};
default:
return state;
}
}
export default reducer;
错误
./src/reducers/reducer.js
Line 16: Parsing error: Unexpected token, expected ","
14 | return {
15 | ...state,
> 16 | action.data.hits
| ^
17 | };
18 | default:
19 | return state;
答案 0 :(得分:3)
您要返回一个对象,因此需要为API响应分配一个密钥。
return {
...state,
images: action.data.hits,
};