简体   繁体   English

如何在 react-native 函数组件中将获取数据设置为文本字段

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

I am learning react-native and have a question about fetching data and passing them to a text component.我正在学习 react-native 并且有一个关于获取数据并将它们传递给文本组件的问题。 I fetched my data from my node.js back-end but don't know how to pass this data to component.我从 node.js 后端获取了数据,但不知道如何将这些数据传递给组件。 Below is the code that i have tried so far.以下是我迄今为止尝试过的代码。

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
 ) 
}

if you have an array of values and you want to show them you can use:如果您有一组值并且想要显示它们,您可以使用:

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>)}
 </>) 
}

if you have a single value just replace your text component with:如果您只有一个值,只需将您的文本组件替换为:

<Text>{details}</Text>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM