我正在尝试解析单个用户输入,但it's throwing an error指出:
未处理的拒绝(TypeError):name.split不是函数
当我尝试搜索创建者的名称时,例如Frank Miller
,它会抛出该错误。
class Creators extends React.Component {
constructor(props) {
super(props);
this.state = {
comics: []
};
}
byCreator = async name => {
var names = name.split(" ");
var firstName = names[0];
var lastName = names[1];
await fetch(
`https://gateway.marvel.com:443/v1/public/creators?firstName=${firstName}%20&lastName=${lastName}&apikey=117b458635106b9721749634b53fb07b`
)
.then(res => res.json())
.then(json => {
const creatorID = json.data.results[0].id;
return fetch(
`https://gateway.marvel.com:443/v1/public/comics?creators=${creatorID}&apikey=117b458635106b9721749634b53fb07b`,
{ cache: "force-cache" }
);
})
.then(res => res.json())
.then(d => this.setState({ comics: d.data.results }));
};
handleChange = event => {
this.setState({ value: event.target.value });
};
render() {
return (
<div>
<div>
<input
type="search"
placeholder="creator"
value={this.state.value}
onChange={this.handleChange}
/>
<button onClick={this.byCreator}>Search</button>
</div>
<ul>
{this.state.comics.map(c => (
<li key={c.id}>
<p> {c.title} </p>
<p> {c.description} </p>
<img src={c.thumbnail.path + "." + c.thumbnail.extension} />
</li>
))}
</ul>
</div>
);
}
}
答案 0 :(得分:0)
您需要创建一个按钮单击句柄,并创建一个将值传递给name参数的调用byCreator:
handleClick: event => {
const valueForNameParam = this.state.value; // or any other string
this.byCreator(valueForNameParam);
}
然后,您必须将新函数(和现有的handleChange函数)绑定到构造函数中对象的实例:
constructor(props) {
super(props);
this.state = {
comics: []
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
最后,您必须将按钮单击事件的绑定从byCreator函数更改为handleClick函数:
<button onClick={this.handleClick}>Search</button>
如果您进行此更改,将解决报告的错误。