我正在尝试将我在 React 中构建的 React 应用程序转换为 React Native。我有一个 onPress
事件绑定(bind)到通过 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} />
))}
</>
);
}
}
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>
);
}
}
最佳答案
根据 this :
componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.
您应该改为从 componentDidMount
生命周期方法运行 axios
请求:
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);
}
}
关于javascript - 试图分配给只读属性 | react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53839934/