未处理的拒绝(错误)减速器未定义返回

时间:2019-02-15 03:25:43

标签: reactjs api redux

服务器在呈现搜索组件时引发错误“未处理的拒绝”。在编写reducer时,我都对这两种情况都做了return声明。

enter image description here

操作文件中的代码

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)});
    }

这是NewsResults.js代码,我正在使用mapStateToProps函数

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();

1 个答案:

答案 0 :(得分:0)

您给化简器的状态是一个列表,您要为其分配值,就像它是一个对象一样。将reducer更改为state = initialState = {}

const initialState = {}
export default function (state = initialState, action) {
switch (action.type) {
        // your cases
    default:
    return state
   }
}