【问题标题】:React JS - Uncaught TypeError: this.props.data.map is not a functionReact JS - 未捕获的类型错误:this.props.data.map 不是函数
【发布时间】:2015-07-20 11:07:29
【问题描述】:

我正在使用 reactjs,但在尝试显示 JSON 数据(来自文件或服务器)时似乎无法阻止此错误:

Uncaught TypeError: this.props.data.map is not a function

我看过:

React code throwing “TypeError: this.props.data.map is not a function”

React.js this.props.data.map() is not a function

这些都没有帮助我解决问题。页面加载后,我可以验证 this.data.props 是否未定义(并且确实具有与 JSON 对象等效的值 - 可以使用 window.foo 调用),因此它似乎没有及时加载由 ConversationList 调用。如何确保 map 方法正在处理 JSON 数据而不是 undefined 变量?

var converter = new Showdown.converter();

var Conversation = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="conversation panel panel-default">
        <div className="panel-heading">
          <h3 className="panel-title">
            {this.props.id}
            {this.props.last_message_snippet}
            {this.props.other_user_id}
          </h3>
        </div>
        <div className="panel-body">
          <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
        </div>
      </div>
    );
  }
});

var ConversationList = React.createClass({
  render: function() {

    window.foo            = this.props.data;
    var conversationNodes = this.props.data.map(function(conversation, index) {

      return (
        <Conversation id={conversation.id} key={index}>
          last_message_snippet={conversation.last_message_snippet}
          other_user_id={conversation.other_user_id}
        </Conversation>
      );
    });

    return (
      <div className="conversationList">
        {conversationNodes}
      </div>
    );
  }
});

var ConversationBox = React.createClass({
  loadConversationsFromServer: function() {
    return $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    this.loadConversationsFromServer();
    setInterval(this.loadConversationsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div className="conversationBox">
        <h1>Conversations</h1>
        <ConversationList data={this.state.data} />
      </div>
    );
  }
});

$(document).on("page:change", function() {
  var $content = $("#content");
  if ($content.length > 0) {
    React.render(
      <ConversationBox url="/conversations.json" pollInterval={20000} />,
      document.getElementById('content')
    );
  }
})

编辑:添加示例 conversations.json

注意 - 调用 this.props.data.conversations 也会返回错误:

var conversationNodes = this.props.data.conversations.map...

返回以下错误:

未捕获的类型错误:无法读取未定义的属性“地图”

这里是 conversations.json:

{"user_has_unread_messages":false,"unread_messages_count":0,"conversations":[{"id":18768,"last_message_snippet":"Lorem ipsum","other_user_id":10193}]}

【问题讨论】:

  • 我已经更新了答案。另外,一些建议:将 propTypes: { data: React.PropTypes.array } 添加到 ConversationList 以验证数据的类型,并添加一个 componentWillUnmount: fn() 来“清除”ConversationBox 中的间隔。

标签: javascript ajax json reactjs


【解决方案1】:

.map 函数仅适用于数组。
data 似乎不是您期望的格式(它是 {},但您期望的是 [])。

this.setState({data: data});

应该是

this.setState({data: data.conversations});

检查“数据”设置为什么类型,并确保它是一个数组。

带有一些建议的修改代码(propType 验证和 clearInterval):

var converter = new Showdown.converter();

var Conversation = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="conversation panel panel-default">
        <div className="panel-heading">
          <h3 className="panel-title">
            {this.props.id}
            {this.props.last_message_snippet}
            {this.props.other_user_id}
          </h3>
        </div>
        <div className="panel-body">
          <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
        </div>
      </div>
    );
  }
});

var ConversationList = React.createClass({
 // Make sure this.props.data is an array
  propTypes: {
    data: React.PropTypes.array.isRequired
  },
  render: function() {

    window.foo            = this.props.data;
    var conversationNodes = this.props.data.map(function(conversation, index) {

      return (
        <Conversation id={conversation.id} key={index}>
          last_message_snippet={conversation.last_message_snippet}
          other_user_id={conversation.other_user_id}
        </Conversation>
      );
    });

    return (
      <div className="conversationList">
        {conversationNodes}
      </div>
    );
  }
});

var ConversationBox = React.createClass({
  loadConversationsFromServer: function() {
    return $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState({data: data.conversations});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },

 /* Taken from 
    https://facebook.github.io/react/docs/reusable-components.html#mixins
    clears all intervals after component is unmounted
  */
  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.map(clearInterval);
  },

  componentDidMount: function() {
    this.loadConversationsFromServer();
    this.setInterval(this.loadConversationsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div className="conversationBox">
        <h1>Conversations</h1>
        <ConversationList data={this.state.data} />
      </div>
    );
  }
});

$(document).on("page:change", function() {
  var $content = $("#content");
  if ($content.length > 0) {
    React.render(
      <ConversationBox url="/conversations.json" pollInterval={20000} />,
      document.getElementById('content')
    );
  }
})

【讨论】:

    【解决方案2】:

    您需要从props.data 创建一个数组,如下所示:

    data = Array.from(props.data);
    

    然后就可以使用data.map()函数了

    【讨论】:

    • 我的类型已经是一个数组,例如typeOf 显示正确的东西,长度也是正确的,但仍然出现错误。这为我修好了。谢谢!
    【解决方案3】:

    更一般地说,您还可以将新数据转换为数组并使用 concat 之类的东西:

    var newData = this.state.data.concat([data]);  
    this.setState({data: newData})
    

    这种模式实际上用于 Facebook 的 ToDo 演示应用程序(参见“应用程序”部分),地址为 https://facebook.github.io/react/

    【讨论】:

    • 这是一个巧妙的提示/技巧,但我想指出,这会掩盖真正的问题并且不会解决 OP。在 OP 的情况下,这将无济于事,因为数据仍将是格式错误的(不是预期的)。对话很可能最终会是空的,因为所有的道具都是空的。我建议不要使用这个技巧,除非你确定你的数据是你想要的格式,所以当返回的数据不是你认为的应该是这样时,你不会出现意外的行为。
    【解决方案4】:

    这是因为组件在异步数据到达之前渲染,你应该控制之前渲染。

    我是这样解决的:

    render() {
        let partners = this.props && this.props.partners.length > 0 ?
            this.props.partners.map(p=>
                <li className = "partners" key={p.id}>
                    <img src={p.img} alt={p.name}/> {p.name} </li>
            ) : <span></span>;
    
        return (
            <div>
                <ul>{partners}</ul>
            </div>
        );
    }
    
    • 当属性为空/未定义时,地图无法解析,所以我先做了一个控制

    this.props &amp;&amp; this.props.partners.length &gt; 0 ?

    【讨论】:

      【解决方案5】:

      我遇到了同样的问题。解决方案是将 useState 初始状态值从字符串更改为数组。 在 App.js 中,之前的 useState 是

      const [favoriteFilms, setFavoriteFilms] = useState('');
      

      我改成

      const [favoriteFilms, setFavoriteFilms] = useState([]);
      

      并且使用这些值的组件停止使用 .map 函数抛出错误。

      【讨论】:

        【解决方案6】:

        有时你只需要检查 api 调用是否有返回数据,

        {this.props.data && (this.props.data).map(e => /* render data */)}
        

        【讨论】:

          【解决方案7】:

          如果你使用 react 钩子,你必须确保 data 被初始化为一个数组。以下是它的外观:

          const[data, setData] = useState([])
          

          【讨论】:

            【解决方案8】:

            您不需要数组来执行此操作。

            var ItemNode = this.state.data.map(function(itemData) {
            return (
               <ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
             );
            });
            

            【讨论】:

            • 兄弟有什么不同?
            【解决方案9】:

            需要将对象转换成数组才能使用map函数:

            const mad = Object.values(this.props.location.state);
            

            其中this.props.location.state 是传递给另一个组件的对象。

            【讨论】:

              【解决方案10】:

              如已接受的答案中所述,此错误通常是由于 API 以某种格式(例如对象)而不是数组返回数据时引起的。

              如果这里没有现有答案可以为您解决问题,您可能希望将您正在处理的数据转换为一个数组,如下所示:

              let madeArr = Object.entries(initialApiResponse)
              

              生成的madeArr 将是一个数组数组。

              每当我遇到此错误时,这对我来说都很好。

              【讨论】:

                【解决方案11】:

                我遇到了类似的错误,但我使用 Redux 进行状态管理。

                我的错误:

                未捕获的类型错误:this.props.user.map 不是函数

                是什么解决了我的错误:

                我将我的响应数据包装在一个数组中。因此,我可以通过数组进行映射。以下是我的解决方案。

                const ProfileAction = () => dispatch => {
                  dispatch({type: STARTFETCHING})
                  AxiosWithAuth()
                    .get(`http://localhost:3333/api/users/${id here}`)
                    .then((res) => {
                        // wrapping res.data in an array like below is what solved the error 
                        dispatch({type: FETCHEDPROFILE, payload: [res.data]})
                    }) .catch((error) => {
                        dispatch({type: FAILDFETCH, error: error})
                    })
                 }
                
                 export default ProfileAction
                

                【讨论】:

                  【解决方案12】:

                  添加这一行。

                  var conversationNodes =this.props.data.map.length&gt;0 &amp;&amp; this.props.data.map(function(conversation, index){.......}

                  这里我们只是检查数组的长度。如果长度大于0,那就去吧。

                  【讨论】:

                    【解决方案13】:
                    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': '2',
                    

                    我在设置修复它时删除了该代码行

                    【讨论】:

                    • 这个答案与问题相关吗?
                    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
                    【解决方案14】:

                    你应该试试这个:

                    const updateNews =  async()=>{
                    
                        const res= await  fetch('https://newsapi.org/v2/everything?q=tesla&from=2021-12-30&sortBy=publishedAt&apiKey=3453452345')
                        const data =await res.json();
                        setArticles(data)
                    }
                    

                    【讨论】:

                      【解决方案15】:

                      从道具数据创建一个数组。

                      let data = Array.from(props.data)
                      

                      那么你可以这样使用它:

                      { data.map((itm, index) => {
                      return (<span key={index}>{itm}</span>)
                      }}
                      

                      【讨论】:

                        【解决方案16】:

                        在获取数据时尝试componentDidMount()生命周期

                        【讨论】:

                        • 另外,请提供一些解释,为什么会这样以及如何工作?
                        猜你喜欢
                        • 1970-01-01
                        • 2018-01-29
                        • 1970-01-01
                        • 2022-11-23
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多