React / Redux:无法映射状态[object Object]

问题描述 投票:1回答:2

试图通过Redux-React-API jungle的黑暗深度定位 - 设法从API和console.log中获取数据 - 但是我和我的谷歌技能都没有设法找出它为什么不渲染。

反应组件

父组件:

class Instagram extends Component {
  componentWillMount(){
    this.props.fetchInfo();
  }

  render() {
    return (
      <div className="container">
        <div className="wrapper">
          <InstagramPost />
        </div>
      </div>
    )
  }
}

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({ fetchInfo }, dispatch);
}

export default connect(null, mapDispatchToProps)(Instagram);

子组件:

class InstagramPost extends Component {
  render() {
    console.log(this.props.info);
    this.props.info.map((p,i) => {
      console.log("PROPS ID: " + p.id);
    })

    return (
      <div>
        <h1>POSTS</h1>
        <ul className="uls">
          {
            this.props.info.map((inf, i) =>
              <li key={i}>{inf.id}</li>
            )
          }
        </ul>
      </div>
    )
  }
}

const mapStateToProps = ({ info }) => {
  return { info }
}

export default connect(mapStateToProps)(InstagramPost);

Redux Action方法:

const ROOT_URL = 'https://jsonplaceholder.typicode.com/posts';

export const fetchInfo = () => {
  const request = axios.get(ROOT_URL);
  return {
    type: types.FETCH_INFO,
    payload: request
  };
}

Redux Reducer方法:

export default function(state = [], action) {
  switch (action.type) {
    case FETCH_INFO:
      return action.payload.data;
    default:
      return state;
  }
}

JSON文件如下所示:

enter image description here

在控制台 - 它工作,我得到我的对象:

enter image description here enter image description here

州也更新:

enter image description here

但是当我映射this.props.info时,尝试渲染this.props.info.id,页面上没有任何内容呈现。令人难以置信的感谢任何输入!

javascript json reactjs redux axios
2个回答
1
投票

有两个问题。正如Mayank Shukla指出的那样,由于没有返回语句的块括号({}),地图回调没有返回任何内容。

另一个问题是减速机。由于info的redux状态是一个用户数组,因此需要在FETCH_INFO上替换旧状态,而不是将获取的数组添加到它的开头。否则,您将维护一组用户数组,每次获取时将增加一个用户数组。

请注意,您不需要对this.props.info进行任何检查,因为它将由reducer和[]初始化为[].map(f) == []

对于redux调试,我非常推荐安装Redux DevTools extension,因为它允许您检查商店的所有更新。每个项目需要一点设置,但这非常值得。

哦,将来,您可能希望不要根据评论/答案中的建议更新您的问题,因为问题将对其他访问者不再有意义:-)


2
投票

看起来你的道具没有在初始渲染上设置。我猜你的API调用还没有完成。

尝试检查变量是否已设置或首先是数组:

像这样的东西:

class InstagramPost extends Component {


render() {

    if(!this.props.info) return null

    return (
      <div>
        <h1>POSTS</h1>
        <ul className="uls">
          {
            this.props.info.map((inf, i) => {
              return <li key={i}>{inf.id}</li>
            })
          }
        </ul>
      </div>
    )
  }
}

const mapStateToProps = ({ info }) => {
  return { info }
}

export default connect(mapStateToProps)(InstagramPost);

或者你可能想检查长度this.props.info.length > 0

© www.soinside.com 2019 - 2024. All rights reserved.