我总是发现 Jest-Enzyme 测试用例以beforeEach类似于以下内容的全局开头:
describe('TEST BLOCK' () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Component />);
));
));
Run Code Online (Sandbox Code Playgroud)
beforeEach全局内部的函数在TEST BLOCK describe块内的每个测试之前运行。在这种情况下,它会在运行每个测试之前浅呈现Component和分配给wrapper。我不太确定为什么我们首先要这样做。我们不是故意放慢测试运行时间吗?渲染一次并分配给它不是可以wrapper吗?这里的目的是beforeEach什么?beforeEach测试 React 组件时是否还有其他有益的场景?
高阶函数定义为:
将函数作为参数和/或返回函数作为返回值的函数。
关闭示例:
function outer() {
const name = 'bob';
function inner(lastName) {
console.log('bob' + lastName);
}
return inner;
}
Run Code Online (Sandbox Code Playgroud)
上面定义的闭包是否属于这一类?看起来他们返回一个函数作为返回值,对吗?
我有一个这样的 React 组件:
class Example extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
address: '',
phone: ''
}
}
componentDidMount() {
//APIcall1 to get name and set the state
//i.e., axios.get().then(this.setState())
//APIcall2 to get address and set the state
//APIcall3 to get phone and set the state
}
}`
Run Code Online (Sandbox Code Playgroud)
如您所见,我发出了三个 API 获取请求以获取详细信息并在获取数据后设置状态三次。因此,我收到此错误:
警告:无法在现有状态转换期间更新(例如在
render组件内部或其他组件的构造函数中)。Render 方法应该是 props 和 state 的纯函数;构造函数的副作用是一种反模式,但可以移至componentWillMount.
顺便说一下,我不会在渲染方法中引起状态变化。无论如何要解决这个问题?