使用React Async渲染数组未定义

时间:2016-09-30 11:44:55

标签: 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的地图

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

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

1 个答案:

答案 0 :(得分:2)

更新:我认为您的问题只是在初始渲染时未定义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>