我正在尝试在es6中使用静态变量.我想count
在Animal
类中声明一个静态变量并增加它.但是,我无法通过声明静态变量static count = 0;
,所以我尝试了另外一种方式:
class Animal {
constructor() {
this.count = 0;
}
static increaseCount() {
this.count += 1;
}
static getCount() {
return this.count;
}
}
console.log(Animal.increaseCount()); // undefined
console.log(Animal.getCount()); // NaN
Run Code Online (Sandbox Code Playgroud)
我希望console.log(Animal.getCount());
如此1
,但它不起作用.如何通过调用方法声明静态变量并对其进行修改?
我想使用反应钩子更改道具,我找到了将 setState 函数作为道具传递给孩子的方法。
容器.tsx
const Container: React.FC = () => {
const [num, setNum] = useState(0);
return <Counter num={num} setNum={setNum} />;
};
Run Code Online (Sandbox Code Playgroud)
Counter.tsx
interface CounterProps {
num: number;
setNum: React.Dispatch<React.SetStateAction<number>>;
}
const Counter: React.FC<CounterProps> = ({ num, setNum }) => {
const handleClick = () => {
setNum(num + 1);
};
return (
// jsx codes...
);
};
Run Code Online (Sandbox Code Playgroud)
它运作良好,但我必须为父组件的每个状态添加两个道具到子组件。有没有更有效的方法来解决这个问题?
我正在使用 webpack 开发服务器来构建单页应用程序。有很多路由,比如/api
, /alpha
, /bravo
... /zulu
,它们都需要被代理。
我编写了 webpack.config.js 文件来代理所有 URL。
proxy: {
"/api": "http://localhost:3000",
"/alpha": {
target: "http://localhost:8080",
pathRewrite: { "^/alpha": "" }
},
"/bravo": {
target: "http://localhost:8080",
pathRewrite: { "^/bravo": "" }
},
"/charlie": {
target: "http://localhost:8080",
pathRewrite: { "^/charlie": "" }
},
...
"/zulu": {
target: "http://localhost:8080",
pathRewrite: { "^/zulu": "" }
},
}
Run Code Online (Sandbox Code Playgroud)
它运行良好,但我不得不编写太多代码。请问有什么办法可以减少吗?我以为 webpack 支持这个问题的正则表达式,但我无法从官方文档中得到解决方案:(
我以为在修改字符串时,rust在堆内存中产生了另一个数据。因此,我预计当将值推入字符串变量时,指针地址会发生变化。
fn main() {
let mut hello = String::from("hello");
println!("{:?}", hello.as_ptr()); // 0x7fcfa7c01be0
hello.push_str(", world!");
println!("{:?}", hello.as_ptr()); // 0x7fcfa7c01be0
}
Run Code Online (Sandbox Code Playgroud)
但是,结果表明并非如此。指针的地址未更改,因此我使用矢量类型对其进行了测试。
fn main() {
let mut numbers = vec![1, 2, 3];
println!("{:?}", numbers.as_ptr()); // 0x7ffac4401be0
numbers.push(4);
println!("{:?}", numbers.as_ptr()); // 0x7ffac4401ce0
}
Run Code Online (Sandbox Code Playgroud)
矢量变量的指针地址在修改时已更改。字符串和向量类型的内存有什么区别?
ecmascript-6 ×1
es6-class ×1
javascript ×1
memory ×1
pointers ×1
proxy ×1
react-hooks ×1
reactjs ×1
rust ×1
typescript ×1
webpack ×1