【问题标题】:React Native fetch data from Express.js serverReact Native 从 Express.js 服务器获取数据
【发布时间】:2018-02-05 20:30:03
【问题描述】:

编辑:已通过切换到不同的 Android 手机模拟器解决此问题

我正在尝试创建一个简单的 React Native 应用程序,它首先会从 Express 后端获取一个 json 文件。

后端:

...data to be fetched up here in a dictionary

//Enable CORS
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.use(bodyParser.json());

app.get('/sightings', (req, res) => {
  res.json(sightings);
});

app.post('/sightings', (req, res) => {
  req.body.id = (sightings.length + 1).toString();
  sightings.push(req.body);
  res.json(req.body);
});

app.get('/species', (req, res) => {
  res.json(species);
});

const port = process.env.PORT ? process.env.PORT : 8081;
const server = app.listen(port, () => {
    console.log("Server listening  port %s", port);
});

前端:

export default class Menu extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            key: '',
            sightings: [],
        }
    }

    componentDidMount() {
        fetch('http://10.0.0.2:3000/sightings')
            .then(res => res.json())
            .then(res => {
                this.setState({sightings: res })
            })
            .catch((error) => {
                console.log(error);
            });
        console.log(this.state.sightings);
    }

显然这里的重点是使用数据更新状态中的目击事件,但它不起作用,我只返回了最初分配给 this.state.sightings 的空对象。

我是否缺少某些步骤?我是使用节点服务器的初学者,我遵循的各种教程就是这样。

data on local host

【问题讨论】:

    标签: javascript reactjs express react-native backend


    【解决方案1】:

    this.setState 是一个异步函数,它需要时间来完成。如果要记录更新的状态,准确的方法是在 this.setState 的回调中记录。这应该可行,

          fetch('http://10.0.0.2:3000/sightings')
                .then(res => res.json())
                .then(res => {
                    this.setState({sightings: res }, () => {
                       console.log(this.state.sightings);
                    })
                })
                .catch ((error) => {
                    console.log(error);
                });
    

    阅读文档以了解 setState 的工作原理,https://reactjs.org/docs/react-component.html#setstate

    【讨论】:

    • 这并没有解决问题,它的行为仍然完全相同
    • 你能在setState之前记录res吗?它显示了什么?
    • 那么似乎是数据获取错误。使用调试模式在代码中设置断点并检查它在哪里不工作
    【解决方案2】:

    好的,伙计们,结果一切正常,但我使用的 Android 模拟器 (Pixel_API_26) 没有。当我切换到 Nexus_4_API_23 时,一切正常。

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多