我正在尝试在开发工具中检查 React Hooks 组件,但无论组件如何,我的所有 useState 挂钩都显示为:
Hooks
State: false
State: null
Effect: fn()
Run Code Online (Sandbox Code Playgroud)
这些false值是正确的,但我无法弄清楚哪个钩子是哪个,因为由于某种原因它们不会显示钩子变量名称。
以下是我设置每个钩子的方法:
const [myHook, setMyHook] = useState(false);
this在处理嵌套函数时如何绑定到React组件?
这是一个骨架的例子.function2嵌套的原因是您可以访问中定义的变量function1
class View extends Component{
constructor(props){
this.function1 = this.function1.bind(this);
this.state = {
a = null;
}
}
componentDidMount(){
function1();
}
function1(){
console.log(this); //will show the component correctly
var param1 = 10;
//call a second function that's defined inside the first function
function2();
function function2(){
console.log(this); //undefined
var a = param1*2;
this.setState({ a : a}); //won't work because this is undefined
}
}
render(){
return(
<div>
<p> Hello </p>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud) 看看其他问题,不清楚在这里做的最好的事情是什么。
我需要从函数 A 调用函数 B。但是函数 B 进行了几次异步调用,我更喜欢使用 async/await 而不是链接承诺。问题变成了,我需要告诉函数 A 等待函数 B 中的所有等待完成。
这是我所做的,确实有效,我想知道这是否是一种反模式。
为了实现这一点,函数 A(异步)调用函数 B,这是一个包含异步函数 C 的承诺。
const functionA = async () => {
await functionB().catch(err => console.error(err));
console.log(' ALL DONE ');
}
const functionB = () => {
return new Promise( (resolve,reject) => {
const functionC = async () => {
const var1 = await make_databaseCall();
const var2 = await make_different_DatabaseCall();
if(!var2) throw Error('var2 is invalid!');
const what_I_need = var1 + var2;
return resolve();
}
//Calling Function …Run Code Online (Sandbox Code Playgroud) 问题:当我的React组件调用导出的函数时,console.log(this)显示undefined.我期待它返回组件,因为我已经在我的构造函数中绑定它.
Leaderboard.js:
import React from 'react';
import {leaderboard, createLeaderboard} from '../utility/gamecode';
class Leaderboard extends React.Component{
constructor(props){
super(props);
this.showLeaderboard = showLeaderboard.bind(this);
this.state = {
}
};
componentDidUpdate(){
if(this.props.leaderboard){
showLeaderboard();
}
}
render(){
return(
<div className="leaderboard hidden">
</div>
)
}
}
export default Leaderboard;
Run Code Online (Sandbox Code Playgroud)
gamecode.js:
export function showLeaderboard(){
console.log(this);
}
//-----------------------
export function createLeaderboard(props){
}
Run Code Online (Sandbox Code Playgroud)