【问题标题】:How to fix state mapping is not a function in React Native?如何修复状态映射​​不是 React Native 中的功能?
【发布时间】:2021-04-08 18:15:14
【问题描述】:

我目前正在学习react native,并探索在列表视图中渲染api数据的过程。现在我已经有了 api 数据,但是当我尝试映射它说的数组时。

TypeError:this.state.readings.map 不是函数。 (在'this.state.readings.map(函数(值){ 返回控制台.log(值); })', 'this.state.readings.map' 未定义)

这里是示例 api:

Sample JSON

在我的 ComponentDidMount 内部:

componentDidMount() {
  
    fetch('http://myip:3000/api/readings/3')
    .then(response => response.json())
    .then(data => this.setState({readings:JSON.stringify(data)}))
}

我的州:

this.state = {
  readings:[],
}

我的渲染:

render() {
    console.log(this.state.readings);
    return (
       
        {

            this.state.readings.map(value => {
                return (
                    console.log(value)
                )
            })

        }         
    )
}

【问题讨论】:

  • 如果您可以将示例添加到代码沙箱中,这将有所帮助。

标签: reactjs react-native


【解决方案1】:

我知道这是使用功能组件,但行为相同

https://snack.expo.io/I0VJsF1z5

问题可能在这一行 .then(data => this.setState({readings:JSON.stringify(data)}))

【讨论】:

  • @Mohammed 我为此使用本机反应。我已经尝试过你的工作,但是它说必须在 组件中呈现文本字符串。
  • 你说得对,我错过了这一点。然后用 试试,看看是否可行
  • @Mohammed 它说错误:文本字符串必须在 组件中呈现。不变
  • 已编辑,如果您可以在此应用程序上分享您的代码,将会很有帮助snack.expo.io
  • 让我试试看。
【解决方案2】:

编辑

如果 this.state.readings 的值为[{"id":1,"AccountNo":"011-001","ConsName":"Jenny Fox.","Address":"Pacific Triad Road."}]

那么这段代码应该可以工作了。

并且由于您的数据正在异步加载。您可以在映射之前添加对 this.state.readings 的检查。

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      readings: [
        {
          id: 1,
          AccountNo: "011-001",
          ConsName: "Jenny Fox.",
          Address: "Pacific Triad Road."
        }
      ]
    };
  }
  render() {
    return (
      this.state.readings.length &&
      this.state.readings.map((value) => {
        console.log(value);
        return <div>{value.Address}</div>;
      })
    );
  }
}

参考:https://codesandbox.io/s/ancient-cdn-5695m?file=/src/App.js:51-484

【讨论】:

  • @DevGe 你想从地图返回什么?
  • 能否为您的 this.state.reading 显示一个输出?
  • 是的,我想返回列表中的所有数据,但是出现错误 TypeError: this.state.readings.map is not a function。 (在 'this.state.readings.map(function (value) { return console.log(value); })' 中,'this.state.readings.map' 未定义)
  • [{"id":1,"AccountNo":"011-001","ConsName":"Jenny Fox.","Address":"Pacific Triad Road."}]跨度>
  • 是的问题:它说在我更改代码后它显示另一个错误,即必须在 组件中呈现文本字符串?\
猜你喜欢
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2020-07-12
  • 2020-07-06
  • 2020-12-29
相关资源
最近更新 更多