【问题标题】:React-Native: How to render variables stored in a POST request on screen?React-Native:如何在屏幕上呈现存储在 POST 请求中的变量?
【发布时间】:2020-07-04 11:45:46
【问题描述】:

我有一个发布路线:

router.post("/projects", async (req, res) => {
  const {
    projectName,
    projectDescription,
    projectBudget,
    projectDuration,
    industry,
    companyName,
    numberOfEmployees,
    diamond,
  } = req.body;
  console.log(diamond);

  const [projectDiamond] = diamond;

  const { criteria } = projectDiamond;

  //diamond is an array containing an object, and that object contains another object called criteria, hence destructuring the 'criteria' object. It's redundant I know but this thing is out of scope of this question!

  if (
    !projectName ||
    !projectDescription ||
    !projectBudget ||
    !projectDuration ||
    !industry ||
    !companyName ||
    !numberOfEmployees ||
    !diamond
  ) {
    return res.status(422).send({ error: "Must provide all project details" });
  }

  try {
    const project = new Project({
      projectName,
      projectDescription,
      projectBudget,
      projectDuration,
      industry,
      companyName,
      numberOfEmployees,
      diamond,
      userId: req.user._id,
    });

    const recommendation = await Recommendation.find({
      "diamond.criteria": criteria,
    }); //Need to render this on screen

    const projectsWithSameDiamond = await Project.find({
      "diamond.criteria": criteria,
    }); //Need to render this on screen
    
    const projectsWithSameIndustry = await Project.find({ industry }); //Need to render this on screen
    
    await project.save();
   
    
  } catch (err) {
    res.status(422).send({ error: err.message });
  }
});

如您所见,这是一个发布请求。现在每次用户说“发布一个新项目”时,我想检索“推荐”和“具有相似钻石的项目”和“具有相似行业的项目”(您可以看到我正在尝试将这三个都保存在发布路线中的不同变量)。

有没有办法检索这三个变量并在 react native 的组件中使用它们?

假设我有一个组件,A.js:

const A = () => {
 return(
  //returning something here
 )
)
}

现在假设这个组件使用 axios 向我定义的路由发送 http post 请求:

const A = () => {
 ...
 axios.post("/projects", {projectName,
    projectDescription,
    projectBudget,
    projectDuration,
    industry,
    companyName,
    numberOfEmployees,
    diamond} );
 return(
  //returning something here
 )
)
}

请求成功完成后(并发布了一个项目)我想说在屏幕上渲染这三个变量

const A = () => {
 return(
  <Text>{recommendation}</Text> {/*Not sure how to do get this after using axios to post new project */}
  <Text>{projectWithSimilarDiamond</Text> {/*Not sure how to do get this after using axios to post new project */}
  <Text>{projectWithSimilarIndustry}</Text> {/*Not sure how to do get this after using axios to post new project */}
 
 )
)
}

【问题讨论】:

    标签: javascript react-native axios


    【解决方案1】:

    这是一个使用状态的例子

    小吃:https://snack.expo.io/@ashwith00/get-post

    代码:

    import * as React from 'react';
    import { Text, View, StyleSheet, ActivityIndicator } from 'react-native';
    import Constants from 'expo-constants';
    import Axios from 'axios';
    
    // You can import from local files
    import AssetExample from './components/AssetExample';
    
    // or any pure javascript modules available in npm
    import { Card } from 'react-native-paper';
    
    export default function App() {
      const [state, setState] = React.useState({
        loading: false,
        data: [],
        error: false,
      });
      const getPosts = async () => {
        setState({
          ...state,
          loading: true,
          data: [],
          error: false,
        });
        // try {
        //   const response = await Axios.post('/users/post', {
        //     //datas
        //   });
        //   setState({
        //     ...state,
        //     loading: false,
        //     data: response.data,
        //   });
        // } catch (err) {
        //   setState({
        //     error: true,
        //   });
        // }
      };
    
      React.useEffect(() => {
        getPosts()
      }, [])
      return (
        <View style={styles.container}>
          {state.loading ? (
            <ActivityIndicator />
          ) : (
            state.data.map(({ title }, key) => {
              <Text {...{ key }}>{title}</Text>;
            })
          )}
        </View>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        paddingTop: Constants.statusBarHeight,
        backgroundColor: '#ecf0f1',
        padding: 8,
      },
      paragraph: {
        margin: 24,
        fontSize: 18,
        fontWeight: 'bold',
        textAlign: 'center',
      },
    });
    
    

    【讨论】:

      猜你喜欢
      • 2022-08-10
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多