0

我正在尝试使用我创建的 API,我遵循了我之前使用过的代码,但是当加载组件时,由于 json 列表为空,它显示为空列表,我可以在日志中看到列表之后正在加载,但组件上没有刷新或任何内容。我尝试添加一个验证,即如果列表的长度为 cero,则不打印任何内容,但这会导致错误。我可以猜到中间件存在问题(我使用的是 redux-promise)。如您所见,我在应用程序定义中添加了中间件,我看不出它缺少什么任何想法?这是我的代码:

动作/index.js:

import axios from 'axios';

export const FETCH_TESTS = 'FETCH_TESTS';
const ROOT_URL = 'http://some-working-api-entry.com';

export function fetchTests(){
  const request = axios.get(`${ROOT_URL}/tests/?format=json`);
  return {
    type: FETCH_TESTS,
    payload: request
  }
}

减速器/reducer_tests.js

import { FETCH_TESTS } from '../actions/index';

export default function(state = [], action){
  switch (action.type) {
    case FETCH_TESTS:
      return [action.payload.data, ...state]; //ES6 syntaxis\   

 }
 return state;
}

动作/index.js

import { combineReducers } from 'redux';
import TestsReducer from './reducer_tests';

const rootReducer = combineReducers({
  tests: TestsReducer
});

export default rootReducer;

容器/list_tests.js

import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchTests } from '../actions';

class TestList extends Component{

    componentDidMount(){
        this.props.fetchTests();
    }

    renderTest(){
      return _.map(this.props.tests, test => {
        return (
          <tr key={test.id}>
            <td>{test.id}</td>
            <td>{test.col1}</td>
            <td>{test.col2}</td>
            <td>{test.col3}</td>
            <td>{test.col4}</td>
        </tr>
        );
      });
  }

  render(){
    return (
      <table className="table table-hover">
        <thead>
          <tr>
            <th>ID</th>
            <th>Col 1</th>
            <th>Col 2</th>
            <th>Col 3</th>
            <th>Col 4</th>
          </tr>
        </thead>
        <tbody>
          { this.renderTest() }
        </tbody>
      </table>
    );
  }
}

function mapStateToProps(state){
    return {tests: state.tests}
  }
//export default connect(mapStateToProps)(TestList)
export default connect(mapStateToProps, { fetchTests})(TestList);

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';

import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
      <App />
    </Provider>
    , document.getElementById('root'));

包.json

{
  "name": "someapp",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.3.2",
    "react-dom": "^16.3.2",
    "react-redux": "^5.0.7",
    "react-scripts": "1.1.4",
    "redux": "^4.0.0",
    "redux-logger": "^3.0.6",
    "redux-promise": "^0.5.3",
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

编辑:从动作创建者(数组包含 api 列表入口点上的唯一对象):

config: Object { timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", … }
​
data: Array [ {…} ]
​
headers: Object { "content-type": "application/json" }
​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }

​ status: 200 ​ statusText: "OK" ​proto : Object { … }

从减速机:

payload:[object Object]

如果我在容器上记录测试道具,首先它记录一个空数组 [] 然后它记录一个长度为 1 的数组

4

2 回答 2

-1

您必须致电调度员来更新商店。

containers/list_tests.js

const mapDispatchToProp = dispatch => ({
      fetchTests : () => dispatch(fetchTests())
})

export default connect(mapStateToProps, mapDispatchToProp )(TestList);

编辑1:发现另一个问题。

export function fetchTests(){
  return axios.get(`${ROOT_URL}/tests/?format=json`)
       .then(res => {
             return {
                type: FETCH_TESTS,
                 payload: res.data
              }
        });

}
于 2018-05-12T13:16:21.913 回答
-1
const request = axios.get(`${ROOT_URL}/tests/?format=json`);
 // here is your issue because axios returns promise.

像这样创建一个 doGet 方法。

export function doGet(url, onSuccess, onFailure) {

        return axios.get(url)
            .then((response) => {
                if (onSuccess) {
                    onSuccess(response);
                }

                return response.data || {};
            })
            .catch((error) => {
                if (onFailure) {
                    onFailure(error);
                }
            });
    }

并按您的喜好调用此方法componentDidMount

doGet(
   'your/api/url',
   (response) => console.log('Api success callback', response),
   (error) => console.log('error callback', error)
)
于 2018-05-12T13:22:10.457 回答