我如何直接将异步存储值分配给状态

时间:2019-03-01 22:27:25

标签: reactjs react-native promise async-await

我需要以下类似的东西 但我无法获得价值

state = {
  phone: async () => await AsyncStorage.getItem('phone')
}

constructor(props){
  super(props)
  alert(this.state.phone);
}

但这不起作用。

我知道如何在componentDidMount中调用它,然后将值传递给状态,它可以正常工作 但是我需要上面类似的东西。

1 个答案:

答案 0 :(得分:1)

这有效:

<html !doctype>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title> Lab7 Baseball Form</title>
    <script type="text/javascript">
        function calculation() {
        var batterName = parseFloat(document.getElementById('battername').value);
        var atBat = parseFloat(document.getElementById('ofbat').value);
        var ofSingles = parseFloat(document.getElementById('ofsingles').value);
        var ofDoubles = parseFloat(document.getElementById('ofdoubles').value);
        var ofTriples = parseFloat(document.getElementById('oftriples').value);
        var ofHome = parseFloat(document.getElementById('ofhome').value);
        var totalBases = ofSingles * 1 + ofDoubles * 2 + ofTriples * 3 + ofHome * 4;
        var slugPercent = totalBases / atBat;
            alert(batterName + slugPercent);
        }
    </script>
</head>

<body>
    <h1>Slugging Percentage Calculator</h1>
    <form>
        <p>Batter's Name:</p> 
        <input type="text" id="battername" /><br />
        <p>Enter number of At Bats:</p>
        <input type="text" id="ofbat" /><br />
        <p>Enter number of Singles:</p>
        <input type="text" id="ofsingles" /><br />
        <p>Enter number of Doubles:</p>
        <input type="text" id="ofdoubles" /><br />
        <p>Enter number of Triples:</p>
        <input type="text" id="oftriples" /><br />
        <p>Enter number of Home Runs:</p>
        <input type="text" id="ofhome" /><br />
        <input type="button" value="Whats his slugging percentage?" onclick="calculation()">
    </form>
</body>
</html>