React native Undefined不是对象(正在计算此.setState';)

React native Undefined不是对象(正在计算此.setState';),react-native,React Native,我从共享首选项中获取值,但当尝试将该值存储在this.state中时,我得到的是上述错误。我想全局访问业务id,以便存储在此.state中。任何帮助都将不胜感激。多谢各位 this.state = { businessId: "" }; SharedPreferences.getItem("business_entity_id",function(value){ this.setState({businessId:value}).bind(thi

我从共享首选项中获取值,但当尝试将该值存储在this.state中时,我得到的是上述错误。我想全局访问业务id,以便存储在此.state中。任何帮助都将不胜感激。多谢各位

this.state = {
  businessId: ""
};

SharedPreferences.getItem("business_entity_id",function(value){
  this.setState({businessId:value}).bind(this);

  console.log("val",this.state.businessId);
}); 

console.log("businessId for shared Preference:", this.state.businessId);

对于函数(){},您可以使用arrow函数()=>{},因为当您使用arrow函数时,它会将其传递给函数

this.state = {
  businessId: ""
};

SharedPreferences.getItem("business_entity_id",(value) => {
  this.setState({businessId:value}).bind(this);

  console.log("val",this.state.businessId);
}); 

console.log("businessId for shared Preference:", this.state.businessId);

您的代码是否在
React.Component
中?不能在
React.Component
之外调用它

这应该起作用:

import React from "react";
import SharedPreferences from "react-native-shared-preferences";

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      businessId: "",
    };
  }

  componentDidMount() {
    SharedPreferences.getItem("key", (value) => {
      this.setState({ businessId: value });
    });
  }

  render() {
    return (
      <View></View>
    );
  }
}
从“React”导入React;
从“react native shared preferences”导入SharedReferences;
类MyComponent扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
businessId:“,
};
}
componentDidMount(){
SharedReferences.getItem(“键”,“值)=>{
this.setState({businessId:value});
});
}
render(){
返回(
);
}
}

更清晰地共享代码您可以在回调中使用箭头函数(值)=>{},而不是函数(值){}。您将在arrow函数中获得全局“this”。导出默认类MainCalendarScreen扩展React.Component{constructor(props){super(props);var SharedReferences=require('React-native-shared-preferences');this.state={businessId:};SharedReferences.getItem(“业务实体\ id”,函数(值){this.setState({bussinessId:value}).bind(this);console.log(“val”,this.state.bussinessId);});console.log(“bussinessId用于共享首选项:,this.state.bussinessId);}我的代码你可以编辑你的问题并在那里添加代码吗?还有,为什么你要绑定你的设置状态?如何使用共享首选项函数的外部值?Exp:当我尝试在控制台中打印该函数的外部值时,它显示函数中未定义的或空的值正在打印,但如何使用共享首选项的外部值rence function?Exp:当我尝试在控制台中打印值时,如console.log(“businessId for shared Preference:”,this.state.businessId);在该函数中,它显示未定义或为空