0

我需要从 API 获取用户 ID,然后将其附加到变量上,这样我就可以将其导出,然后将其用作其他对象中的值。有人可以帮我举个例子吗?我该怎么做?我只坚持在控制台上显示它。

这是我的代码:

class LoginScreen extends Component {

  constructor(){
           super();
           this.state = {
            email: '',
            password: '',
            id: 0,
            result: false,
           }
       }

    _userLogin() {
      
         let email = this.state.email;
         let password = this.state.password;
         
         if (email && password) { 
           fetch("https://URL/api/login", {
             method: "POST",
             headers: {
               'Content-Type': 'application/json'
             },
             body: JSON.stringify({
               email: email,
               password: password,
             })
            })
           .then((response) => {
            if(response.status !== 200) {
              throw new Error('The given data was invalid.')
            }
            return response.json();
            })
           .then((responseData) => {
             this.renderResults(responseData)
             console.log(responseData)
             this.props.navigation.navigate('IntroScreen');
           })
           .catch((err) => console.log(err.message))
         }
       }

    componentDidMount () {
      fetch("https://URL/api/login", {
             method: "GET",
            })
          .then((response) => response.json())
          .then((responseJson) => {
             this.setState({getId: responseJson});
             console.log(responseJson.data.id);
             const id = responseJson.data.id;
          })
          .catch((error) => {
              console.error(error);
          });
    }

       renderResults = (responseData) => {
           if(responseData){
                this.setState({
                    result: true
                })
           }
       }

       handleEmail = (text) => {
             this.setState({ email: text })
       }


       handlePassword = (text) => {
             this.setState({ password: text })
       }

       errorMessage = () => {
         Alert.alert(
           'Error',
           'The given data was invalid.',
           [
            {
              text: "OK",
              style: "cancel"
            },
           ],
          { cancelable: false }
         )
       }

  render() {
    return (...)

将它附加到变量后,我想在其他对象中使用它,例如:

class HomeScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
         currentDate: new Date(),
         markedDate: moment(new Date()).format("YYYY-MM-DD"),
         isLoading: true,
         id: 1, <------- HERE
         name: '',
         floor: 0
        };
    }
4

1 回答 1

0

这是一个快速的代码片段来解决您的问题。

创建一个单例类 gloablParams.js,如下所示

class GlobalParams {
  constructor() {
    this.id = null;
  }
  userId = (id)=>{
    if(!id) return this.id;
    this.id = id;
  }
}
const instance = new GlobalParams()
export default  instance;

现在LoginScreen,您可以像这样导入它

import gp from './gloablParams'; 

现在登录成功后调用这个函数,我认为它的componentDidMount_userLogin并提供id来保存它。

componentDidMount() {
 fetch("https://URL/api/login", {
  method: "GET",
 })
  .then((response) => response.json())
  .then((responseJson) => {
   this.setState({ id: responseJson.data.id });
   gp.userId(responseJson.data.id); //save it here
   console.log(responseJson.data.id);
  })
  .then(gp.userId(id))
  .catch((error) => {
   console.error(error);
  });
}

现在您可以像我上面写的那样以相同的方式导入它,并从同一个函数访问用户 ID,但不带参数

gp.userId() //without any arguments
于 2020-10-09T10:22:40.717 回答