试图分配给只读属性React-Native

时间:2018-12-18 19:38:24

标签: javascript reactjs react-native

我正在尝试将我在React中构建的React应用程序转换为React Native。我有一个onPress事件绑定到一个组件,该事件通过Axios来获取数据,setState使用该数据,然后将其映射到一个处理数据布局的组件,非常简单。但是,我遇到了Attempted to assign to readonly property错误,并且非常模糊,不确定哪里出了问题。即使我能对这个错误堆栈的含义有所了解,也要有所帮助,在此先感谢! <3

import React, { Component } from "react";
    import axios from "axios";
    import NewSongLayout from "./NewSongLayout";
    export default class NewSongData extends Component {
      state = {
        songData: []
      };
      async componentWillMount() {
        try {
          const songList = await axios.get(
            "https://beatsaver.com/api/songs/new/{start?"
          );
          this.setState({
            songData: songList.data.songs
          });
          console.log(this.state.songData);
        } catch (error) {
          console.log(error);
        }
      }
      render() {
        return (
          <>
            {this.state.songData.map(song => (
              <NewSongLayout key={song.id} song={song} />
            ))}
          </>
        );
      }
    }

The error log onPress事件:

import React, { Component } from "react";
import { Text, View, StyleSheet, Button } from "react-native";
import NewSongData from "../Components/NewSongData";

const styles = StyleSheet.create({
  container: {
    display: "flex",
    backgroundColor: "black",
    height: "100%",
    width: "100%"
  },
  text: {
    fontFamily: "Bangers",
    fontSize: 50,
    color: "white",
    textAlign: "center"
  }
});

export default class Landing extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>Beat Saber Companion</Text>
        <Button title="Newest Maps" onPress={NewSongData} />
      </View>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

根据this

  

componentWillMount()在安装之前立即被调用。在render()之前调用它,因此在此方法中设置状态不会触发重新渲染。避免在此方法中引入任何副作用或订阅。

您应该改为通过axios生命周期方法运行componentDidMount请求:

componentDidMount() {
    try {
      const songList = await axios.get(
        "https://beatsaver.com/api/songs/new/{start?"
      );
      this.setState({
        songData: songList.data.songs
      });
      console.log(this.state.songData);
    } catch (error) {
      console.log(error);
    }
  }

答案 1 :(得分:0)

我主要在项目中使用npm并意外执行了yarn命令。通过深入研究,我观察到两个锁定文件。删除yarn-lock.json对我有用。