reactjs - 如何将状态更新为特定值?
问题描述
我希望你们一切都好。
如果你们中的任何人能对以下问题有所了解,我将不胜感激。
有两个相关的组件:
使用 GraphQL 获取数据的父组件
let authors = "";
const { loading, data } = useQuery(FETCH_AUTHORS_QUERY);
console.log(`Loading: ${loading}`);
//console.log(data);
if (data) {
authors = { data: data.getAuthors };
}
return (
<Grid columns={3}>
<Grid.Row className="page-title">
<h1>Recent Essays</h1>
</Grid.Row>
{loading ? (
<h1>Loading essays..</h1>
) : (
authors.data &&
authors.data.map(author => (
<Grid.Column key={author.id} style={{ marginBottom: 20 }}>
<AuthorCard author={author} />
</Grid.Column>
))
)}
<Grid.Row></Grid.Row>
</Grid>
);
}
const FETCH_AUTHORS_QUERY = gql`
{
getAuthors {
id
Author
Description_1
Description_2
}
}
`
- 名为“AuthorCard”的子组件(您可以看到放置在上面的父组件中):
function AuthorCard({ author: { Author, Description_1, id } }) {
const [writer, setWriter] = useState();
return (
<Card fluid>
<Card.Content>
<Image
floated="right"
size="mini"
src="https://image.cnbcfm.com/api/v1/image/105691887-1556634687926ray.jpg?v=1576249072"
/>
<Card.Header>{Author}</Card.Header>
<Card.Meta as={Link} to={`/essays`}></Card.Meta>
<Card.Description>{Description_1}</Card.Description>
</Card.Content>
<Card.Content extra>
<Button as="div" labelPosition="right">
<Button color="teal" basic>
<Icon name="heart" />
</Button>
<Label basic color="teal" pointing="left"></Label>
</Button>
<Button labelPosition="right" as={Link} to={`/essays`}>
<Button
color="blue"
basic
key={Author.id}
onClick={() => setWriter(Author)}
>
<Icon name="comments" />
</Button>
</Button>
</Card.Content>
</Card>
);
}
export default AuthorCard;
问题如下:
当我单击子组件中的 as={Link} to={ /essays
} 按钮时,我想将“setWriter”状态设置为我单击其按钮的单个作者。
但是,我无法指定单击其按钮的单个作者。React 认为我想为整个作者列表“设置作家”。例如,当我在按钮内使用 console.log(Author) 时,我可以看到控制台中打印的列表中的每个作者。
我尝试使用 event.target .value 和 onChange 而不是 onClick 添加 id。
我只是无法针对单个作者来更新状态(这将在不同的组件中需要)。
如果有任何不清楚的地方或者提供更多详细信息是否会有所帮助,请告诉我。
在此先感谢,祝您编码愉快!!!
担
解决方案
您应该使用解构赋值表达式,它可以将数组中的值或对象中的属性解包到不同的变量中。
我认为您应该像这样声明您的子组件:
function AuthorCard({ Author, Description_1, id }) {
...
...
...
}
推荐阅读
- javascript - 如何在 Javascript 中的 onClick 事件侦听器中传递字符串值,就像我们在 html 中的 onclick 事件侦听器中所做的那样
- r - 如何创建网格搜索以找到最佳参数?
- oracle - 如果在 oracle 或 informatica 中的字符串末尾存在字符 _00 或 .00,则删除字符
- pytorch - 为什么广播会给出一个空的张量?
- go - 模块和导入文件夹的问题
- mercurial - 如何在用户权限受限的远程 Linux 主机上安装和运行 Mercurial 服务器?
- ios - UIsearchController 支持哪些语言?
- php - 您知道如何仅为自定义帖子类型创建类别吗?
- python - ImportError:“packaging.requirements”包是必需的
- three.js - GLSL 随着时间的推移平滑地改变网格的温度(颜色)