Reactjs React PropTypes.array具有类型为string的键

Reactjs React PropTypes.array具有类型为string的键,reactjs,Reactjs,我的组件有一个定义为数组的属性,但我不能用数字键迭代这些值。这些键似乎是字符串类型。 我错过什么了吗 类测试扩展了React.Component{ 渲染(){ 让parse=[]; for(让我输入Object.keys(this.props.test)){ parse.push( {i} {typeof i}{this.props.test[i]} ) } 返回( {parse} ) } } Test.propTypes={ 测试:React.PropTypes.array } ReactDO

我的组件有一个定义为数组的属性,但我不能用数字键迭代这些值。这些键似乎是字符串类型。 我错过什么了吗

类测试扩展了React.Component{
渲染(){
让parse=[];
for(让我输入Object.keys(this.props.test)){
parse.push(
{i} {typeof i}{this.props.test[i]}
)
}
返回(
{parse}
)
}
}
Test.propTypes={
测试:React.PropTypes.array
}
ReactDOM.render(
, 
document.getElementById('main')
);
显示属性测试的键是字符串


在您的情况下,如果您想使用数字键进行迭代,只需使用
map
forEach
或经典的
for
循环,以下是
map
示例:

this.props.test.map((el, i) => (
  <div key={i}>
    {i} {typeof i} {el}
  </div>
))
this.props.test.map((el,i)=>(
{i} {typeof i}{el}
))
使用非数字键完全可以。此外,有时使用索引作为键不是一个好主意


例如,如果您的数组可能更改排序或删除/插入开头或中间的元素,React可能会执行许多不必要的操作(卸载/重新装载它们)

在您的情况下,如果要使用数字键进行迭代,只需使用
map
forEach
或经典的
进行
循环,以下是
map
示例:

this.props.test.map((el, i) => (
  <div key={i}>
    {i} {typeof i} {el}
  </div>
))
this.props.test.map((el,i)=>(
{i} {typeof i}{el}
))
使用非数字键完全可以。此外,有时使用索引作为键不是一个好主意


例如,如果您的阵列可能更改排序或删除/插入开头或中间的元素,React可能会执行许多不必要的操作(卸载/重新装载它们)

您可以更好地在阵列上组织代码调用映射函数

class Test extends React.Component {
  render () {
    const {test} = this.props;

    return (
       <div>
         {test.map((t, i) =>
            <div key = {i}>{i} {typeof i} {t}</div>
         )}
       </div>
    );
   }
}

Test.propTypes = {
  test: React.PropTypes.array
};

ReactDOM.render(
    <Test test={["a", "b", "c"]} />, 
    document.getElementById('main')
);
类测试扩展了React.Component{
渲染(){
const{test}=this.props;
返回(
{test.map((t,i)=>
{i} {typeof i}{t}
)}
);
}
}
Test.propTypes={
测试:React.PropTypes.array
};
ReactDOM.render(
, 
document.getElementById('main')
);

您可以更好地组织阵列上的代码调用映射功能

class Test extends React.Component {
  render () {
    const {test} = this.props;

    return (
       <div>
         {test.map((t, i) =>
            <div key = {i}>{i} {typeof i} {t}</div>
         )}
       </div>
    );
   }
}

Test.propTypes = {
  test: React.PropTypes.array
};

ReactDOM.render(
    <Test test={["a", "b", "c"]} />, 
    document.getElementById('main')
);
类测试扩展了React.Component{
渲染(){
const{test}=this.props;
返回(
{test.map((t,i)=>
{i} {typeof i}{t}
)}
);
}
}
Test.propTypes={
测试:React.PropTypes.array
};
ReactDOM.render(
, 
document.getElementById('main')
);

因为如果您编写
{1:'foo'}
,JavaScript对象的键总是stringsEven,因此
1
将成为stringsEven,但我将属性定义为[“a”、“b”、“c”]。它还将PropTypes设置为array。请参阅
Object.keys
的文档,这里:Object.keys()返回一个数组,其元素为strings,因为JavaScript对象的键总是stringsEven如果您编写
{1:'foo'}
,则
1
将成为strings,但我将属性定义为[“a”、“b”、“c]。它还将PropTypes设置为array。请参见
Object.keys
此处的文档:Object.keys()返回元素为字符串的数组
对象。这里不需要keys
,它已经是一个字符串数组,您可以直接在
上使用map。props.test
:)
对象。这里不需要keys
,它已经是一个字符串数组,您可以直接在
this.props.test
:)上使用map