Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

javascript - oneOfType PropTypes如何接受未定义的值?(How oneOfType PropTypes can accept undefined value?)

I have strange behavior with PropTypes .

(我对PropTypes有奇怪的行为。)

I have a component named ColumnAct.

(我有一个名为ColumnAct的组件。)

const ColumnAct = ({ header, values }) => {

...

ColumnAct.propTypes = {
   header: PropTypes.string,
   values: PropTypes.oneOfType[(PropTypes.string, PropTypes.array)],
}

It is used liked this :

(喜欢这样使用:)

<ColumnAct header={"Asker"} values={act && act.asker} />

But when the values is undefined , the validation is KO because it considers that undefined is not a string or array, which is pretty fair.

(但是,当值undefined ,验证为KO,因为它认为undefined不是字符串或数组,这很公平。)

But how to add the possibility of undefined in a oneOfType syntax?

(但是,如何在oneOfType语法中添加undefined的可能性?)

I tried to add to force the values to a string with a defaultProps , which would be a good an appropriate workaround.

(我尝试使用defaultProps添加强制值到字符串的方法,这将是一个不错的适当解决方法。)

ColumnAct.defaultProps = {
   values: "",
}

Unfortunately, the defaultProps seems to be invoked after the validation process.

(不幸的是,似乎在验证过程之后调用了defaultProps 。)

I hope not to be obliged to modify all my call of the component with an empty string as a fallback...

(我希望没有义务用空字符串修改我对组件的所有调用,以作为后备...)

Any idea?

(任何的想法?)

Edit: the problem seems to happen only for a Next.js context.

(编辑:问题似乎只发生在Next.js上下文中。)

I made 2 projects in CodeSanbox to verify it:

(我在CodeSanbox中进行了2个项目来进行验证:)

Edit 2: Now, I can reproduce the problem in React too.

(编辑2:现在,我也可以在React中重现该问题。)

I am really confused :(

(我真的很困惑:()

  ask by pom421 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...