【问题标题】:Use result of a query as input for a button function使用查询结果作为按钮功能的输入
【发布时间】:2022-11-01 20:59:28
【问题描述】:
我想获取查询结果并将其用于按钮功能,以更改父组件的状态。在此代码示例中,父组件的状态包含一个 ID,用于稍后显示一些内容。我想为我的数据库的每组数据创建一个按钮,并使用集合的 ID 来更改状态。但是当我这样实现它时,ID 变为“NaN”。有什么可能的方法来完成这项工作吗?
class TestClass extends React.Component{
constructor(props) {
super(props);
this.handleNewID = this.handleNewID .bind(this);
this.state = {
ID: 0,
};
}
handleNewID ({id}){
this.setState({ID: id});
}
render(){
const props={
handleNewID :this.handleNewID ,
}
return(
<div>
<TestFunction props={props}/>
</div>)
}
}
function TestFunction ({props}){
const {loading, error, data} = useQuery(GET_SOMETHING);
if (loading) return <p>Loading ...</p>;
if (error) return <p>Error ... ${JSON.stringify(error, null, 2)}</p>;
if (data)
return data.something.map(({ id }) => (
<div>
<button onClick={ () => props.handleNewID ({id})}> Test Button </button>
</div>));
}
【问题讨论】:
标签:
javascript
reactjs
react-hooks
setstate
【解决方案1】:
这里有很多事情要解决;我决定在代码中包含 cmets,而不是在答案中描述我的更改。
这可能无法解决问题,但它应该指导您进行故障排除。
class TestClass extends React.Component {
constructor(props) {
super(props);
this.handleNewID = this.handleNewID.bind(this); // removed space, probably copy/paste issue
this.state = {
ID: 0,
};
}
handleNewID(id) {
if(isNaN(id)) { // if we get NaN we log out to see what value id is, this will help us with troubleshooting
console.log(`Id is NaN. Current value of id: ${id}`)
}
// no need to wrap in braces
this.setState({ ID: Number(id) }); // try to convert to Number to be consisten with data types
}
render() {
// removed props object since it can be confusing
// instead we're passing the handler directly as an onClick-property
return (
<div>
<TestFunction onClick={this.handleNewID} />
</div>
);
}
}
function TestFunction({ onClick }) {
const { loading, error, data } = useQuery(GET_SOMETHING);
if (loading) return <p>Loading ...</p>;
if (error) return <p>Error ... ${JSON.stringify(error, null, 2)}</p>;
if (data) {
return data.something.map(({ id }) => (
<div>
<button onClick={() => onClick(id)}>Test Button</button>
</div>
));
}
return null; // always need to return something from a component
}