【发布时间】:2019-07-09 04:21:27
【问题描述】:
服务器在渲染搜索组件时抛出错误“未处理的拒绝”。在编写 reducer 时,我在这两种情况下都添加了 return 声明。
动作文件中的代码:
export const NEWS = "NEWS";
export function news(items) {
const action = {
type: NEWS,
items
}
return action;
}
Reducer 文件中的代码:
import { NEWS } from '../actions';
export default function news
(state = [], action) {
switch(action.type) {
case NEWS:
console.log("News are ",action.items);
return {...state, news: action.items};
default:
return state;
}
}
这是我的搜索功能。
class Search extends Component {
constructor(props) {
super(props);
this.state = {
query: ''
};
}
search(){
console.log('Search button clicked', this.state.query);
const url = `http://hn.algolia.com/api/v1/search?query=${this.state.query}`;
// console.log(url);
fetch(url, {
method: 'GET'
}).then(response=> response.json())
.then(jsonObj => {this.props.news(jsonObj.results)});
}
这是我使用 mapStateToProps 函数的 NewsResults.js 代码
import React, { Component } from 'react';
import Search from './Search';
import { connect } from 'react-redux';
class NewsResults extends Component {
render() {
return (
<div>
<h2>
Search Results:
</h2>
<Search/>
</div>
)
}
};
function mapStateToProps(state) {
console.log(state)
return {
news: state.news
}
};
export default connect(mapStateToProps, null)(NewsResults);
** 这就是我的 redux 存储在 index.js 中的样子**
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById('root'));
registerServiceWorker();
【问题讨论】:
-
试试
state = [{}], -
你想要的数据形状是什么?
state=[]或state={ news: [] }? -
@codekaizer 我都试过了,但没有成功。我只是想获取我搜索的新闻列表。
-
等待,错误提示未处理的拒绝。所以你的请求失败了,不是
catched。尝试在then之后添加.catch(error => console.log(error))以查看详细错误。 -
catch error 没有帮助,因为它只是给出了同样的错误。我在问题中编辑了更多我的反应代码,可能对我有用。 @codekaizer