Redux连接组件不会从状态

时间:2018-04-11 14:58:50

标签: javascript reactjs redux

我有来自API的API图片库。我存储了具有redux状态的图像的数组。问题是我的<Gallery>组件的道具没有得到状态更改。

我读过它可能是因为reducer中的状态突变,但我的reducer只使用concat来添加图像。我还尝试使用componentWillReceiveProps()componentWillMount()来删除actons。什么都没有帮助。州正在更新,但this.props.images仍为空。

其他变体是因为异步图像获取,但是如何以及为什么?

App.jsx

import React, {Component} from 'react';
import {createStore, compose, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';

import {galleryReducer} from '../../reducers/galleryReducer';

import {Gallery} from "../Gallery/Gallery";
import './App.css';

function middleware({dispatch, getState}) {
  return next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState);
    }

    return next(action);
  };
}

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const store = createStore(
  galleryReducer,
  undefined,
  composeEnhancers(
    applyMiddleware(middleware)
  )
);

class App extends React.Component {
  render() {
    return (
      <Provider store={store}>
          <Gallery />
      </Provider>
    );
  }
}

export default App;

Gallery.jsx

import React, {Component} from 'react';
import {connect} from 'react-redux';

import {Picture} from "../Picture/Picture";

import {store} from "../../store";

import './Gallery.css'


class GalleryComponent extends Component {
  constructor() {
    super();
    this.state = {
      photoIndex: 0,
      isOpen: false
    };
    this.openLightbox = this.openLightbox.bind(this);
  }

  async load() {
    const url = 'url';
    fetch(url)
      .then((resp) => resp.json())
      .then((data) => {
        let results = data.hits;
        console.log(results); //successful
        store.dispatch({
          type: 'APPEND_IMAGES',
          images: results
        });

        console.log('IMAGES:', this.props.images); //empty
      })
      .catch(function (error) {
        console.log(error);
      });
  }


  componentDidMount() {
    this.load();  
  }

  openLightbox(index) {
    this.setState({
      isOpen: true,
      photoIndex: index
    });
  }

  render() {
    const {photoIndex, isOpen} = this.state,
          images = this.props.images;
    return (
        <section className="gallery">
          {images.map((item, index) => <Picture openLightBox={this.openLightbox}
                                                key={item.id}
                                                index={index}
                                                imgData={item}/>)}
        </section>


    );
  }
}

const stateToProps = (state) => ({
  images: state.images,
  page: state.page,
  error: state.error
});

export const Gallery = connect(stateToProps)(GalleryComponent);

galleryReducer.js

const initialState = {
  images: [],
  loading: false,
  page: 1,
  error: null
};

export const galleryReducer = function(state = initialState, action) {

  switch (action.type) {
    case 'APPEND_IMAGES':
      return {
        ...state,
        images: state.images === undefined ? action.images : state.images.concat(action.images),
        loading: false
      };
    default:
      return state
  }
};

0 个答案:

没有答案