闭包小结

直接上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import React, { useState } from 'react';
import { Form } from 'antd';
import { ContainerOutlined } from '@ant-design/icons';
import axios from 'axios';
const App = (props) => {
const [fileList, setFilelist] = useState([]);
const onFinish = (values) => {
axios();
};
const uploadProps = {
action: 'https://run.mocky.io/v3/12a88009-751e-4cc0-8d03-c47d970fae45',
onChange: (info) => {
let fileList = [...info.fileList];
fileList = fileList.slice(-1);
fileList = fileList.map((file) => {
return file;
});
setFilelist(fileList);
},
};
const Child = (props) => {
return (
<Upload fileList={fileList} {...uploadProps}>
<ContainerOutlined />
</Upload>
);
};
const [form] = Form.useForm();
return (
<div>
<Form form={form} onFinish={onFinish}>
<Child test={test}></Child>
</Form>
</div>
);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React, { useState } from 'react';
import { Form } from 'antd';
import { ContainerOutlined } from '@ant-design/icons';
import axios from 'axios';
const App = (props) => {
const [fileList, setFilelist] = useState([]);
const onFinish = (values) => {
axios();
};
const uploadProps = {
action: 'https://run.mocky.io/v3/12a88009-751e-4cc0-8d03-c47d970fae45',
onChange: (info) => {
let fileList = [...info.fileList];
fileList = fileList.slice(-1);
fileList = fileList.map((file) => {
return file;
});
setFilelist(fileList);
},
};
const [form] = Form.useForm();
return (
<div>
<Form form={form} onFinish={onFinish}>
<Upload fileList={fileList} {...uploadProps}>
<ContainerOutlined />
</Upload>
</Form>
</div>
);
};

遇到的问题是这样的:上面两段代码表现不一致。下面的代码可以成功执行上传,上面的请求则会被 canceled。

代码很简单,第一段是用 Child 又封了一层,第二段代码则没有。

(此处省略一大段探索的过程……)

结论:是由闭包产生的问题,Child 直接用了外面的值,而不是从参数传进去,本身就是闭包了。

提示:函数里面套函数定义,不够清楚的时候很容易拿到错的值。

解决方法:使用第二段代码(原需求需要条件渲染,在这里可以使用条件表达式),如果一定要封装起来,应该独立到父组件的外面。

扩展:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var foo = (function () {
var secret = 'secret';
//'闭包'内的函数可以访问secret变量,而secret变量对于外部却是隐藏的
return {
get_secret: function () {
//通过定义的接口来访问secret
return secret;
},
new_secret: function (new_secret) {
//通过定义的接口来修改secret
secret = new_secret;
},
};
})();
foo.get_secret(); //得到'secret'
foo.secret; //Type error,不能访问
foo.new_secret('a new secret'); //通过函数接口,我们访问并修改了secret变量
foo.get_secret(); //得到'a new secret'

参考:

闭包 1

闭包 2

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信