首页 > 解决方案 > 如何将状态更新为特定值?

问题描述

我希望你们一切都好。

如果你们中的任何人能对以下问题有所了解,我将不胜感激。

有两个相关的组件:

使用 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
    }
  }
`

  1. 名为“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。

我只是无法针对单个作者来更新状态(这将在不同的组件中需要)。

如果有任何不清楚的地方或者提供更多详细信息是否会有所帮助,请告诉我。

在此先感谢,祝您编码愉快!!!

标签: reactjsuse-state

解决方案


您应该使用解构赋值表达式,它可以将数组中的值或对象中的属性解包到不同的变量中。

我认为您应该像这样声明您的子组件:

function AuthorCard({ Author, Description_1, id }) {
  ...
  ...
  ...
}

推荐阅读