类型错误:无法读取未定义的属性'map' - React



我正在处理一个搜索字段,我想将数据返回给用户,但我得到了错误:TypeError:无法读取未定义的属性"map"。,我似乎不明白为什么地图没有定义

这是我的代码:代码沙盒

我尝试从j-fiddle(下面的代码(中提取示例代码,并将其转换为一个功能组件。这是我试图从j-fiddle 中操作的代码

class Wrapped extends React.Component {
constructor(props){
super(props)
this.state = {
results: []
}

this.search = this.search.bind(this)
}
search(results){
this.setState({results})
}
render(){
const { results } = this.state
return (
<div>
<Search onSearch={this.search} />
<Result {...this.state} />
</div>
)
}
}
class Search extends React.Component {
constructor(props){
super(props);
this.state = {
searchValue: ''
}
this.handleOnChange = this.handleOnChange.bind(this);
}

handleOnChange(e){
this.setState({
[e.target.name]: e.target.value
}, () => {
setTimeout(() => {
// it can be the result from your API i just harcoded it
const results = ['hello', 'world', 'from', 'SO'].filter(value => value === this.state.searchValue)
this.props.onSearch(results)
}, 1000)
})  
}

render(){
return (
<div>
Search: <input name="searchValue" type="text" onChange={this.handleOnChange} />
</div>
)
}
}
const Result = ({results}) => {
return (
<ul>
{results.map(result => <li key={result}>{result}</li>)}
</ul>
)
}
ReactDOM.render(
<Wrapped/>,
document.getElementById('container')
);

我正在检查您的代码,并在Wrapped.js:中发现以下错误

<Results {...results} />

由于results声明如下:

const [results, setResults] = useState([]);

{...results}会以一种糟糕的方式将内容数组扩展到属性中,我建议您在此处阅读有关Spread Operator的信息。

为了修复您的错误,您可以执行以下解决方案之一:

简单的解决方案

<Results results={results} />

价差操作员解决方案

...
const resultsProps = {
results,
}
...
return (
<>
<SearchComp onSearch={search} />
<Results {...resultsProps} />
</>
);
...

希望这对你有用,请让我知道并记住阅读关于Spread Operator的内容,它是.JS.中一个非常有用的函数

相关内容

最新更新