REACT使用redux

时间:2018-06-08 11:48:44

标签: node.js mongodb reactjs express redux

我有一个快速应用程序连接与代理作出反应 我已经设法显示我的数据,但现在我想在redux soo中显示:

有我的问题,我已经制作了所有减速器/动作和存储但我没有在我的页面中看到任何数据

有我的代码:

行动:

export const api = ext => `http://localhost:8080/${ext}`;

//
// ─── ACTION TYPES ───────────────────────────────────────────────────────────────
//

export const GET_ADVERTS = "GET_ADVERTS";
export const GET_ADVERT = "GET_ADVERT";

//
// ─── ACTION CREATORS ────────────────────────────────────────────────────────────
//

export function getAdverts() {
  return dispatch => {
    fetch("/adverts")
      .then(res => res.json())
      .then(payload => {
        dispatch({ type: GET_ADVERTS, payload });
      });
  };
}

export function getAdvert(id) {
  return dispatch => {
    fetch(`/adverts/${id}`)
      .then(res => res.json())
      .then(payload => {
        dispatch({ type: GET_ADVERT, payload });
      });
  };
}

reducer:

import { combineReducers } from "redux";
import { GET_ADVERTS, GET_ADVERT } from "../actions/actions";
const INITIAL_STATE = {
  adverts: [],
  advert: {}
};

function todos(state = INITIAL_STATE, action) {
  switch (action.type) {
    case GET_ADVERTS:
      return { ...state, adverts: action.payload };
    case GET_ADVERT:
      return { advert: action.payload };
    default:
      return state;
  }
}

const todoApp = combineReducers({
  todos
});

export default todoApp;

index.js

//imports...

const store = createStore(todoApp, applyMiddleware(thunk));

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,

  document.getElementById("app")
);

我的广告列表页面:

//imports..

class Adverts extends Component {


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

  render() {
    const { adverts = [] } = this.props;

    return (
      <div>
        <Header />
        <h1>Adverts</h1>
        {adverts.map(advert => (
          <li key={advert._id}>
            <a href={"adverts/" + advert._id}>
              {advert.name} {advert.surname}
            </a>
          </li>
        ))}

        <Footer />
      </div>
    );
  }
}

const mapStateToProps = state => ({
  adverts: state.adverts
});

export default connect(
  mapStateToProps,
  { getAdverts }
)(Adverts);

谢谢:)

1 个答案:

答案 0 :(得分:0)

在您需要的页面中,您应该有

  import React , {Component} from 'react'
  import { connect }from 'react-redux'
  import { getAdvert } from '...action.js'

  class example  extends Component{

componentWillMount(){
  this.props.getAdvert()
}
    render(){
      return(
<div>
hello
</div>
      )
    }
  }
const mapStateToProps = ({}) => {
    return{}
  }
  export default connect (mapStateToProps,{getAdvert})(example)

在mapstatetoprops中,您从redux

返回值