尝试转到文章页面时出现问题

时间:2018-10-19 07:04:09

标签: reactjs redux

我从App组件出发的路线

<Route path="/articles/:id" component={ArticleDetail} />

我的组件

class ArticleDetail extends Component {

constructor(props) {
    super(props);
    this.state = {
        articleId: props.match.params.id,
        article: this.props.articleDetail(props.match.params.id),
    };
}

// componentDidMount() {
//     this.props.articleDetail(this.state.articleId)
// };

componentWillMount() {
    this.props.articleDetail(this.state.articleId)
};

render() {
    console.log('state', this.state);
    console.log('props', this.props);
    return (
        <div className="article-container">
            <h3 className="article-headline">{this.state.article.headline}</h3>
            {
                this.state.article.img_name &&
                <img src={require('../images/articles/' + this.state.article.img_name)} alt=""/>
            }
            <p className="article-description">{this.state.article.description}</p>
            <p>
                <span>Published at {this.state.article.created} by </span>
                <span className="username">{this.state.article.author.username}</span>
            </p>
        </div>
    )
}
}

const mapStateToProps = state => {
  return {
    articles: state.articles,
    article: state.article,
  }
};

const mapDispatchToProps = dispatch => {
  return {
    articleDetail: (id) => {
        dispatch(articles.articleDetail(id)).then((res) => {console.log('fetch', res)});
    }
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(ArticleDetail);
来自mapDispatchToProps的

console.log从api返回了我的文章: {type:“ GET_ARTICLE”,文章:{…}}

我的减速器:

import {FETCH_ALL_ARTICLES, GET_ARTICLE} from "../constants";


const initialState = [];

export default function articles(state=initialState, action) {

  switch (action.type) {

    case FETCH_ALL_ARTICLES:
      return [...state, ...action.articles];

    case GET_ARTICLE:
      // return [...action.article];
      console.log(action.article);
      return action.article;

   default:
     return state;
  }
}

但是无论是道具还是状态,我都没有在组件中得到数据。 从代码中可以看到,我尝试使用两个不同的钩子直接在构造函数中创建它。希望对您有所帮助。我在做什么?

1 个答案:

答案 0 :(得分:0)

mapStateToProps中,您引用了state.article,但它是undefined。您需要在状态下创建密钥article。在减速器中:

const initialState = {};

export default function articles(state = initialState, action) {

  switch (action.type) {

    case FETCH_ALL_ARTICLES:
      return { ...state, { articles: action.articles } };

    case GET_ARTICLE:
      return { ...state, { article: action.article } };

   default:
     return state;
  } 

}

mapStateToProps中:

const mapStateToProps = state => {
  return {
    articles: state.articles,
    article: state.article,
  }
};

我还没有测试过,但是应该可以。