javascript - 使用 React Async 渲染数组未定义

标签 javascript reactjs react-redux redux-thunk

我正在从 REST 服务检索数据。数据以数组形式返回。这是我用来检索数据的函数。

export function fetchMessage() {
  return function(dispatch) {
    axios.get(`${ROOT_URL}/currencies`, {
      headers: { token: localStorage.getItem('token') }
    })
     .then(response => {
       console.log(response.data);
       dispatch({
         type: FETCH_MESSAGE,
         payload: response.data
       });
     });
  }
}

fetchMessage 的输出是一个对象数组。

[Object, Object, Object, Object, Object, Object]
0:Object
    addedDate:"2013-08-22"
    ccyCode:"CHF"
    country:"SCHWIZER FRANC"
    lastChangeDate:"2016-05-02"
    offerRate:7.02
    prevRate:8.501
    prevRateDate:"2016-04-01"
    rate:8.425
    rateDate:"2016-05-01"
    unit:1
    __proto__:Object
1:Object
2:Object
3:Object
4:Object
5:Object

fetchMessage 函数由下面的组件调用。

class Feature extends Component {
  componentWillMount() {
    this.props.fetchMessage();
    //console.log(this.props);
  }

  render() {
    return (
      <div>{this.props.message}</div>
    );
  }
}

function mapStateToProps(state) {
  return { message: state.auth.message };
}

export default connect(mapStateToProps, actions)(Feature);

该组件无法呈现消息,因为它是一个

bundle.js:1256 Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {ccyCode, country, unit, rateDate, rate, prevRateDate, prevRate, offerRate, addedDate, lastChangeDate}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `Feature`.(…)

我尝试像这样运行 this.props.message 的 map

<div>
        {this.props.message.map(
          function(object){
            return ('Something'
            );
          }
        )}
</div>

但我收到一条错误消息,指出我无法在 message 上运行 map。如何渲染对象中的数据?我需要以其他方式保存它吗?如何迭代对象来渲染它们?

最佳答案

更新:我认为您的问题只是 this.props.message 在初始渲染时未定义。如果未设置,请尝试渲染 null

render() {
  if (!this.props.message) return null
  return (
    <div>
      {this.props.message.map(message => {
        return (
          <div key={message.ccyCode}>...
            {message.ccyCode} {message.rate} ...
          </div>
        )
      })}
    </div>
  )
}

如果有人对动态渲染对象感兴趣,我下面的回答可能仍然有帮助。

我假设您想要动态呈现对象中的数据,而不是必须显式呈现每个字段。

尝试迭代Object.keys并渲染数据。

<div>
    {Object.keys(this.props.message).map(key => {
        return (
          <div key={key}> // you need a dynamic, unique key here to not get a React warning
            {key}: {this.props.message[key]}
          </div>
        )
      }
    )}
</div>

如果您只想显示数据以进行调试/检查,我发现这非常有帮助。

<pre>
  {JSON.stringify(this.props.message,null,2)}
</pre>

关于javascript - 使用 React Async 渲染数组未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39790784/

相关文章:

javascript - 在phonegap中读取pdf文件

javascript - Material UI 自动完成全宽

reactjs - 如何在 react 中将 react 钩子(Hook)对象从 index.js 传递到 axios 拦截器

react-native - 使用 redux observable 显示警报框

javascript - 有没有更短的方法在 mapStateProps 中编写/表示它?

javascript - 我可以使用 JS Lint、JS Hint 或其他工具来防止将错误数量的参数传递给方法吗?

javascript - 在 Service-Worker 中使用 Crypto Node.js 加密并使用 window.crypto 解密

node.js - 使用 react js 和 express API 服务器使用 fetch 发布一个对象

javascript - 我可以仅在某些条件下添加 React 输入事件处理程序吗?

javascript - 打开相对于鼠标位置的 CSS3/HTML5 模态对话框