我有一个表单,我要求用户输入几个字段的字段值,将字段值存储在状态中并以自定义格式显示状态值。
所以,我有几个输入字段和一个提交按钮:
<button onClick={this.handleSubmit}>Submit</button>
{
this.state.credentials &&
//<Credentials value={this.state}/>
<Credentials value={JSON.stringify(this.state, undefined, 2)} />
}
Credentials 函数将组件的状态转换为 JSON 格式:
const Credentials = ({value} ) => {
return <pre>{formatState(value)}</pre>;
}
formatState 函数将基本上操纵状态值并以我想要的方式显示它们:
function formatState(state) {
console.log("hi")
console.log(state);
const output = state.groups.reduce((final, s)=> {
console.log(output)
const values = Object.keys(s).reduce((out, o)=> {
out[o] = s[o].map(k => Object.values(k))
return out;
}, {})
final = {...final, ...values}
return final;
}, {})
console.log(output)
}
状态如下所示:
{
"groups": [
{
"typeA": [
{
"name": "abc"
},
{
"number": "13,14"
}
],
"typeB": [
{
"country": "xyz"
},
{
"date1": "2019-05-14"
}
]
}
]
}
但我想要这样的输出:
groups: {
"typeA": [[abc],[13,14]],
"typeB": [[2019-05-14],[xyz]]
}
SO,reduce 函数用于将状态转换为以下输出。但我收到错误:
“类型错误:无法读取未定义的属性‘reduce’”
请谁能告诉我为什么会这样。
最佳答案
错误在这里 <Credentials value={JSON.stringify(this.state, undefined, 2)} />
. JSON.stringify
生成某个对象的字符串表示(在您的情况下为 this.state
)。参数 state
的 formatState
具有字符串类型。看来你想要state
争论是对象。所以你应该做
<Credentials value={this.state} />
关于json - 类型错误 : Cannot read property 'reduce' of undefined in react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56141404/