【问题标题】:How can i pass data from promise to props in react我如何将数据从承诺传递到反应中的道具
【发布时间】:2020-12-06 23:46:23
【问题描述】:

我是新来的反应,我想将我的数据从我的安全存储传递到道具。但是我现在不知道如何正确处理promise函数并提取它的数据。

当我像这样传递数据时,我的对象是未定义的。

这是我的代码。

const Authenticate = () => {
  
    //const [deviceId, setDeviceId] = useState("");
    //SecureStore.deleteItemAsync("device_id").then((reject) => {
    //});

    //const resp = {code : 3, expositions : 5}

    SecureStore.getItemAsync("device_id").then((response) => {
      //setDeviceId({"id" : response});
      console.log("stored id : " + response);
      //let resp = sendId({'id' : response})
      test(response);
    }
);

      function test (info){
        return info;
      }

      return (
        <Expositions infections={test()}/>
      );
};
export default Authenticate;

【问题讨论】:

    标签: reactjs promise


    【解决方案1】:

    你真的应该阅读this

    const Authenticate = () => {
      
        const [myStuff, setMyStuff] = useState();
        
        //this will be executed on mount
        useEffect(()=>{
          SecureStore.getItemAsync("device_id").then((response) => {
             setMyStuff(response)
            }
          );
        },[])
          
       console.log(myStuff) 
     }
    

    第一次渲染时myStuffundefined,然后在获取数据后,setMyStuff 将触发新的渲染,您将看到更新后的数据

    【讨论】:

    • 我的secureStore.getItemAsync函数在useEffect中没有被调用
    • 我没有足够的信息,伙计,如果您在获取数据之前和之后放置日志,您会看到代码正在被调用。但我不知道 SecureStore 是什么,你确定你获取数据正确吗?
    【解决方案2】:

    使用 react state hook 存储 promise 提供的数据,然后将 state 传递给渲染的 jsx。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2018-10-07
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      相关资源
      最近更新 更多