开发者问题收集

无法从 React Hook 状态获取值

2019-11-11
1173

我是 React Native 和 Hooks 的新手。在我的项目中,我声明了两个状态属性,我想在函数中获取它们。但我没有从 Hooks 属性中获取值。在控制台中,它显示 [object object]

const Login =()=> {
  const [username, setUserName] = React.useState('');
  const [password, setPassword] = React.useState('');

  callAPI = async ()=>{
    console.log('api called :' + username)
  }
}
2个回答

这是您要尝试完成的工作示例。

function mockAPI(username,password) {
  return new Promise((resolve,reject) => {
    setTimeout(()=>resolve(`The API received username: ${username} and pwd: ${password}`),1000);
  });
}

function App() {
  
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  
  function callMockAPI(user,pwd) {
    mockAPI(user,pwd)
    .then((result)=>console.log(result));
  }
  
  return(
    <React.Fragment>
      <div>
        Username: <input type='text' value={username} onChange={()=>setUsername(event.target.value)}/>
      </div>
      <div>
        Password: <input type='password' value={password} onChange={()=>setPassword(event.target.value)}/>
      </div>
      <div>
        <button onClick={()=>callMockAPI(username,password)}>Submit</button>
      </div>
    </React.Fragment>
  );

}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
cbdeveloper
2019-11-11

得到解决方案我在这行 onChange={()=>setPassword(event.target.value) 上犯了一个错误

现在通过这行解决了

onChangeText={text => setPassword(text)

Utpal
2019-11-12