簡體   English   中英

如何在 react-native 函數組件中將獲取數據設置為文本字段

[英]How to set fetch data to text field in react-native function component

我正在學習 react-native 並且有一個關於獲取數據並將它們傳遞給文本組件的問題。 我從 node.js 后端獲取了數據,但不知道如何將這些數據傳遞給組件。 以下是我迄今為止嘗試過的代碼。

const TableView = () => {
  const [details, setDetails] = useState('');

  const getUserData = async () => {
        fetch('https://----.herokuapp.com/getIncomePerUser', {
          method: 'post',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            email: data,
            month: value,
          }),
        })
          .then(response => response.json())
          .then(response => {
            console.log('Test');
            console.log(response);
            const array = response;
            for (const i of array) {
              const total = i.total;
              setDetails(total);
              console.log(total);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
  };


  useEffect(() => {
    getUserData();
  }, []);

  return (
 <Text Value={details}></Text> //I need to set my fetch data this text component
 ) 
}

如果您有一組值並且想要顯示它們,您可以使用:

const TableView = () => {
  const [details, setDetails] = useState('');

  const getUserData = async () => {
        fetch('https://----.herokuapp.com/getIncomePerUser', {
          method: 'post',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({
            email: data,
            month: value,
          }),
        })
          .then(response => response.json())
          .then(response => {
            setDetails(response.map(r => r.total));
          })
          .catch(err => {
            console.log(err);
          });
      });
  };


  useEffect(() => {
    getUserData();
  }, []);

  return (<>
    {details.map((d, i) => <Text key={i}>{d}</Text>)}
 </>) 
}

如果您只有一個值,只需將您的文本組件替換為:

<Text>{details}</Text>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM