未调用ComponentDidMount

时间:2018-12-14 06:36:52

标签: reactjs redux redux-thunk

我正在尝试使用Redux和Thunk来获取数据。我不知道为什么在其他组件中可以正常工作的代码在这种情况下会停止工作-状态只是没有收到正确的数据,因为在ComponentDidMount中没有触发应调用服务器的函数。
组件。

class SparePartDetails extends Component {

    componentDidMount() {
        const path = this.preparePath(this.props.location.pathname)
        this.props.fetchDetails(path);
    }

    preparePath = (path) => {
        const segments = path.split('/');
        const filter = segments.length > 2 ? segments[2] : '';
        const id = segments.length > 2 ? segments[3] : '';
        return `${Constants.apiUrl}/${Constants.paths.spareparts}/${filter}/${id}`;
    }

    render() {
        return (
            <div className={styles.container}>
                <h1> <FontAwesomeIcon size='xs' icon='cog' /> Детали запчасти</h1>
                <main className={styles.details_container}>
                    <section className={styles.flex}>
                        <h2>Фотографии</h2>
                        <SparePartImages id={this.props.details[0].Id}/>
                    </section>
                    <section className={styles.flex}>
                        <h2>Описание</h2>
                        <ul>
                            <li>
                                Название: {this.props.details[0].Name}
                            </li>
                            <li>
                                Чертежный код: {this.props.details[0].BlueprintCode}
                            </li>
                            <li>
                                Категория: <NavLink 
                                    className={styles.navigation__item__link} 
                                    activeClassName= {styles.active} 
                                    to={`/spareparts/categories/${this.props.details[0].CategoryId}`}>
                                    {this.props.details[0].Category}
                                </NavLink>
                            </li>
                            <li>
                                Производитель: {this.props.data.Manufacturer}
                            </li>
                            <li>
                                Единица измерения: {this.props.details[0].Unit}
                            </li>
                            <li>
                                Количество в упаковке {this.props.details[0].ItemsPerPack}
                            </li>
                            <li>
                                Длина. В упаковке: {this.props.details[0].LengthInPack} / Без упаковки: {this.props.details[0].LengthNoPack}
                            </li>
                            <li>
                                Глубина. В упаковке: {this.props.details[0].DepthInPack} / Без упаковки: {this.props.details[0].DepthNoPack}
                            </li>
                            <li>
                                Высота. В упаковке: {this.props.details[0].HeightInPack} / Без упаковки: {this.props.details[0].HeightNoPack}
                            </li>
                        </ul>
                    </section>
                    <section className={styles.flex}>
                        <h2>Кто продает</h2>
                        <SparePartSuppliers id={this.props.details[0].Id}/>
                    </section>
                </main>
            </div>
        )
    }
 }

export default withRouter(SparePartDetails)

容器

const mapStateToProps = state => ({
  details: console.log(state.sparepartdetails.data),
  loading: state.sparepartdetails.loading,
  error: state.sparepartdetails.error
})

const mapDispatchToProps = dispatch => ({
  fetchDetails: path => dispatch(fetchSparepartDetails(path))
})

export default connect(mapStateToProps, mapDispatchToProps)(SparePartDetails)

动作

export const fetchSparepartDetailsBegin = () => ({
    type: ActionTypes.sparePartDetailsActions.FETCH_DATA_BEGIN
});

export const fetchSparepartDetailsSuccess = sparepart => ({
    type: ActionTypes.sparePartDetailsActions.FETCH_DATA_SUCCESS,
    payload: {
        sparepart
    }
});

export const fetchSparepartDetailsFailed = error => ({
    type: ActionTypes.sparePartDetailsActions.FETCH_DATA_FAILED,
    payload: {
        error
    }
});

export function fetchSparepartDetails(path) {
    return async dispatch => {
        dispatch(fetchSparepartDetailsBegin());
        try {
            const res = await axios.get(path);
            dispatch(fetchSparepartDetailsSuccess(res.data));
        }
        catch (error) {
            return dispatch(fetchSparepartDetailsFailed(error));
        }
    }
}

减速器

const initialState = {
    data: [],
    loading: false,
    error: null
  };

  export default function sparepartDetailsReducer(state = initialState, action) {
    switch(action.type) {
      case ActionTypes.sparePartDetailsActions.FETCH_DATA_BEGIN:
        return {
          ...state,
          loading: true,
          error: null
        };

      case ActionTypes.sparePartDetailsActions.FETCH_DATA_SUCCESS:
      const s = {
        ...state,
        loading: false,
        data: action.payload.sparepart
      };
      console.log(s) 
        return {
          ...state,
          loading: false,
          data: action.payload.sparepart
        };

      case ActionTypes.sparePartDetailsActions.FETCH_DATA_FAILED:
        return {
          ...state,
          loading: false,
          error: action.payload.error,
          data: []
        };

      default:
        return state;
    }
  }

1 个答案:

答案 0 :(得分:0)

这可能与一些异步内容有关。并已解决:

render() {
        if (this.props.details && this.props.details.length > 0) {
            return (
                <div className={styles.container}>
相关问题