我还在学习React-Redux。我理解如何检索简单的JSON数组/对象。但是,我不知道如何调用嵌套对象。当捆绑这个时,我正在查看'after'对象 - t3_5t61fz - 显然是因为我正在调用data.after,但是当我尝试实现data.title时,没有任何内容出现。我想抓住标题并在控制台中查看:
减速机:
export default function reducer(state={
data: {
data: {}
},
fetching: false,
fetched: false,
error: null,
}, action) {
switch(action.type){
case "FETCH_DATA":{
return {...state, fetching:true}
}
case "FETCH_DATA_REJECTED":{
return {...state, fetching: false, error: action.payload}
}
case "FETCH_DATA_FULFILLED":{
return {...state, fetching: false, fetched: true, data: action.payload}
}
case "ADD_DATA":{
return {...state, data: [...state.data, action.payload]}
}
case "UPDATE_DATA":{
const { id, title } = action.payload
const newData = [...state.data]
const dataToUpdate = newData.findIndex(data => data.id === id)
newData[dataToUpdate] = action.payload;
return {...state, data: newData}
}
case "DELETE_DATA":{
return {...state, data: state.data.filter(data => data.id !== action.payload)}
}
}
return state
}
动作
import axios from 'axios';
export function fetchData(){
return function(dispatch){
axios.get("https://www.reddit.com/r/webdev/top/.json")
.then((response) => {
dispatch({ type: "FETCH_DATA_FULFILLED", payload: response.data})
})
.catch((err) => {
dispatch({type: "FETCH_DATA_REJECTED", payload: err})
})
}
}
export function addData(id, text){
return {
type: 'ADD_DATA',
payload:{
id,
data,
},
}
}
export function updateData(id, text){
return {
type: 'UPDATE_DATA',
payload: {
id,
data,
},
}
}
export function deleteData(id){
return {
type: 'DELETE_DATA',
payload: id
}
}
Layout.js
import React from "react"
import { connect } from "react-redux"
import { fetchData } from "../actions/dataActions"
@connect((store) => {
return {
data: store.data.data
};
})
export default class Layout extends React.Component {
componentWillMount() {
this.props.dispatch(fetchData())
}
render() {
const { data } = this.props;
return <div>
<h1>{data.data.after}</h1>
</div>
}
}
答案 0 :(得分:0)
我正在调用data.after,但是当我尝试实现data.title时,没有出现
我看到data.after
是一个数组,并且您正在尝试获取该数组中第一个项目的数据标题。
您应该可以通过<h1>
{data.data.after[0].data.title}
中的数据
我很好奇为什么数据以这种方式如此深深地嵌套。