首页 > 解决方案 > 如何在 react-native 功能组件中将获取数据设置为文本字段

问题描述

我正在学习 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
 ) 
}

标签: reactjsreact-nativereact-hooksfetch-api

解决方案


如果您有一个值数组并且想要显示它们,您可以使用:

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>

推荐阅读