我想先创建一个电子商务网站,然后通过React和Redux从api获取产品

时间:2019-04-01 21:10:58

标签: reactjs redux

这是我的化简页面,我正在从json占位符获取虚拟数据

    import axios from "axios";
var x = [];
axios.get("https://jsonplaceholder.typicode.com/users")
    .then(res => {
       x= res.data
        console.log(x)
    })

const initState = {
    count: 0,
    data: x


}


const reducer = (state = initState , action) =>{  }

/// app.js页面:::

function mapStateToProps(state){
  return{
    count: state.count,
    data : state.data

  }
}

我无法在app.js中显示项目,请帮助

3 个答案:

答案 0 :(得分:0)

您应该将初始数据放入提供者组件中。通常在index.js或App.js中完成。 App.js应该是类组件,并且在componentDidMount()函数中调用此API并获取响应。然后更新提供程序中的存储,以使redux知道初始状态。

答案 1 :(得分:0)

它不是那样工作的-您无法在reducer中进行异步初始化。不过,您可以在操作文件或组件中进行操作。

const initState = {
    count: 0,
    data: x // x is loaded async so this won't work
}

const reducer = (state = initState , action) =>{  }

您可以将其放在这样的操作文件中:

// assuming redux-thunk is installed
export const myAction = args => dispatch => {
  axios.get(...).then(results =>
    dispatch({type: 'INITIALISE_MY_DATA',
              payload: results}) )
}

然后,您将在减速器中处理INITIALISE_MY_DATA动作。

答案 2 :(得分:0)

获取数据时,首先必须调度更改,因此您可以基于此操作在reducer中更改状态。 这是

的代码
// todoController.js
function todoController (req, res) {
    res.send('Hello i am todo controller')
} 

// index.spec.js
const express = require('express');
const request = require('request-promise');
const todoController = require('./todoController');
jest.mock('./todoController');

const app = express();

app.get('/todo', todoController)

test('If certain routes are calling the correct controller , controller should to have been called times one.', async() => {
    await request({url: 'http://127.0.0.1/todo'})
    expect(todoController).toHaveBeenCalledTimes(1);
})

以及您的组件

//do this in componentDidMount of your app root component
import axios from "axios";
//get data
var x = [];
axios.get("https://jsonplaceholder.typicode.com/users")
    .then(res => {
       x= res.data
        store.dispatch(type: "ACTION_TYPE", payload: x) //action type could be anything,

    })

//reducer
const initState = {
    count: 0,
    data: x
}

const reducer = (state = initState , action) =>{
    const newState = {...state};
    switch(action.type){
      case "ACTION_TYPE": //this should match action you have dispatched
        newState.count = action.payload.count;
        newState.data = action.payload.data;
        return newState;
    }
}

请注意,如果您的数据是数组,则可能应该首先映射槽数组并为每个值生成元素,例如:

import { connect } from 'react-redux';

class YourComponent extends React.Component{
render(){
    return (
     <div>
       {this.props.data}
     </div>
    )
    }
}
function mapStateToProps(state){
  return{
    count: state.count,
    data : state.data

  }
}

export default connect(mapStateToProps)(YourComponent)