gpt4 book ai didi

javascript - 在浅层渲染的功能组件上调用 instance() 返回 null

转载 作者:行者123 更新时间:2023-12-03 13:42:04 25 4
gpt4 key购买 nike

我有以下 React 功能组件,它接受名称作为 prop

const Name = ({ name }) => <h1>{name}</h1>;

Name.propTypes = {
name: PropTypes.string.isRequired
}

我的测试如下

describe("<Name />", () => {
it("accepts name as a prop", () => {
const wrapper = shallow(<Name name="Monkey D Luffy"/>);
expect(wrapper.instance().props.name).toBe("Monkey D Luffy");
})
})

这将返回以下错误

TypeError: Cannot read property 'props' of null

更新

我按如下方式调用名称组件

class Person extends React.Component {
state = {name: "Name here"}
render () {
return <div><Name name={this.state.name} /></div>
}
}

我发现在无状态组件上调用 instance() 无法与 React 16 一起使用。* 在我的情况下,我无法使用 wrapper.prop()它只返回根节点的 props

为什么在渲染组件上调用实例函数时返回 null 以及如何测试传递到无状态组件的 props?

原始问题

为什么在渲染组件上调用实例函数时返回null

最佳答案

instance() === null 对于功能组件,因为功能组件没有实例。

应该使用 Enzyme 自己的 API 来访问组件属性:

expect(wrapper.prop('children')).toBe("Monkey D Luffy");

the reference解释说,

To return the props for the entire React component, use wrapper.instance().props. This is valid for stateful or stateless components in React 15.. But, wrapper.instance() will return null for stateless React component in React 16., so wrapper.instance().props will cause an error in this case.

关于javascript - 在浅层渲染的功能组件上调用 instance() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53791304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com