无法从反应挂钩状态获取值

时间:2019-11-11 13:10:03

标签: reactjs react-native react-hooks

我是本机和钩子的新手。在我的项目中,我声明了两个状态属性,我想将它们包含在一个函数中。但是我没有从钩子属性中获取值。在控制台中,它正在编写[object object]

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

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

2 个答案:

答案 0 :(得分:1)

这是一个您试图实现的外观的可行示例。

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"/>

答案 1 :(得分:0)

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

现在此行已解决

onChangeText = {文本=> setPassword(文本)}