json - 无法访问 JSON 对象信息 React/Redux

标签 json reactjs redux

感觉我在这里遗漏了一些明显的东西 - 但我不知道如何访问我的 JSON 数据。我有一个容器组件:

class About extends Component {
  componentDidMount(){
    const APP_URL = 'http://localhost/wordpress/'
    const PAGES_URL = `${APP_URL}/wp-json/wp/v2/pages`

    this.props.fetchAllPages(PAGES_URL, 'about')
  }

  render(){
    return (
      <div>
        <Header/>
        <div className="bg">
          <div className="home-wrapper">
            <h1>AAAAABBBBBOOOOUUUUUT</h1>
            <Counter/>
            <AboutInfo />
          </div>
        </div>
        <Footer/>
      </div>
    )
  }
}

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

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

还有一个智能组件:

class AboutInfo extends Component {
  render(){
    console.log(this.props.page);
    console.log(this.props.page.id);
    return (
      <div>
        <h1>This is ID: {this.props.page.id}</h1>
      </div>
    )
  }
}

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

export default connect(mapStateToProps)(AboutInfo);

我的行动:

export const fetchAllPages = (URL, SLUG) => {
  var URLEN;

  if(!SLUG){
    URLEN = URL
  } else {
    URLEN = URL + "?slug=" + SLUG
  }

  return (dispatch) => {
    dispatch(fetchRequest());
    return fetchPosts(URLEN).then(([response, json]) => {
      if(response.status === 200){
        if(!SLUG) {
          dispatch(fetchPagesSuccess(json))
        } else {
          dispatch(fetchPageBySlugSuccess(json))
        }
      } else {
        dispatch(fetchError())
      }
    })
  }
}

const fetchPageBySlugSuccess = (payload) => {
  return {
    type: types.FETCH_PAGE_BY_SLUG,
    payload
  }
}

我的 reducer :

const page = (state = {}, action) => {
  switch (action.type) {
    case FETCH_PAGE_BY_SLUG:
      console.log(action.paylod)
      return action.payload
    default:
      return state
  }
}

这给了我:

enter image description here

当我在 AboutInfo 组件中使用 console.log(this.props.page) 时,它会打印该对象,但是当我打印 console.log(this.props.page.id) 时,它会给我未定义。为什么无法打印 JSON 内容?谢谢!

最佳答案

page 是一个数组,因此 this.props.page.id未定义。您可能想要访问数组中的第一个元素,在这种情况下您会这样做

this.props.page[0].id

但您可能还需要添加测试,因为在响应可用之前,您将尝试访问 page[0].id 并且它可能会中断。

你可以改写

this.props.page && this.props.page[0] && this.props.page[0].id

关于json - 无法访问 JSON 对象信息 React/Redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49272926/

相关文章:

json - 使用 PowerQuery 从列表中的 JSON 记录中提取逗号分隔值

javascript - 序列化一个奇怪的js对象

c - 如何在Ubuntu 14.0LTS中正确安装cjson?

javascript - Django - json 响应允许 json[i][j] 引用而不是 json[0].field.field_name

javascript - 在 react 中添加新项目到数组开头时出现问题

javascript - 收到警告: promise 以非错误被拒绝:Turbo中的[object String]

javascript - 为什么 Curry Redux 中间件 : state => next => action {} vs. (state, next) => action {}

javascript - 在 React js 中根据 API 响应显示消息

reactjs - 为什么我的 React 应用程序将外部 URL 附加到 http ://localhost:/<port> and not to ONLY the URL itself?

reactjs - 使用有状态组件绕过 redux 是一种不好的做法吗?