类型错误:“状态”是只读的

我正在尝试从 axios 请求渲染数据,但收到错误:TypeError:“state”是只读的。我试图弄清楚如何在手机屏幕上显示来自获取请求的数据。我以前从未这样做过,但我看到的很多文章都有人使用下面的方法。


export default function App() {

  const [state, setState] = useState();


  state = {

    items: [],

  };


  const url = "";


  const getAPOD = () => {

    axios

      .get(url)

      .then(function (response) {

        // handle success

        let title = response.data.title;

        console.log(response.data);

        setState({

          items: title,

        });

      })

      .catch(function (error) {

        // handle error

        console.log(error);

      });

  };


  return (

    <View style={styles.container}>

      <Text>{items.title}</Text>

      <StatusBar style="auto" />

    </View>

  );

}


猛跑小猪
浏览 142回答 1
1回答

杨魅力

您必须像下面这样设置状态&nbsp;const [state, setState] = useState({items:[]});您可以像以前一样直接分配状态。最好像下面这样更改代码。export default function App() {&nbsp; const [state, setState] = useState({&nbsp; &nbsp; items: {title:""},&nbsp; });&nbsp;&nbsp;&nbsp; useEffect(getAPOD,[]);&nbsp; const url = "";&nbsp; const getAPOD = () => {&nbsp; &nbsp; axios&nbsp; &nbsp; &nbsp; .get(url)&nbsp; &nbsp; &nbsp; .then(function (response) {&nbsp; &nbsp; &nbsp; &nbsp; // handle success&nbsp; &nbsp; &nbsp; &nbsp; let title = response.data.title;&nbsp; &nbsp; &nbsp; &nbsp; console.log(response.data);&nbsp; &nbsp; &nbsp; &nbsp; setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; items: title,&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; .catch(function (error) {&nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; &nbsp; &nbsp; console.log(error);&nbsp; &nbsp; &nbsp; });&nbsp; };&nbsp; return (&nbsp; &nbsp; <View style={styles.container}>&nbsp; &nbsp; &nbsp; <Text>{state.items.title}</Text>&nbsp; &nbsp; &nbsp; <StatusBar style="auto" />&nbsp; &nbsp; </View>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript