简体   繁体   English

如何从另一个组件更改反应组件的 state

[英]how to change state of a react component from another component

I saw dozens of examples but they are not working in my case, I want to update the page variable in "bookitem" component and rerender it.我看到了几十个例子,但它们在我的情况下不起作用,我想更新“bookitem”组件中的页面变量并重新渲染它。 using gives an error ' Expected an assignment or function call and instead saw an expression no-unused-expressions' using 给出一个错误'期望一个赋值或 function 调用,而是看到一个表达式 no-unused-expressions'

    import React from 'react'
import { Pagination, Container } from 'semantic-ui-react'
import bookitem  from './Book_item'

const PaginationI = () => (
    <Container style={{textAlign: "center", padding:'4rem'}}>
  <Pagination defaultActivePage={5} totalPages={10} onPageChange={PageChange}/>
  </Container>
)

function PageChange(event,data){
    console.log(data.activePage);
    <bookitem page={data.activePage}/>
};
export default PaginationI

////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////// ///////////////////////////////////////// //

 class bookitem extends Component{

    constructor(props){
        super (props);

        this.state={
            counter:0,
            page:0,
            data2:[]

        };
    }

    componentWillMount(){
        console.log(this.props.page)
            axios.get('/books/'+this.state.page).then(res=>{console.log(res.data);this.setState({data2:res.data});})
            console.log('aa')
            console.log(this.state.data2)


    }

    genurl(isbn){
        console.log(isbn)
    let url='http://covers.openlibrary.org/b/isbn/'+ isbn + '-L.jpg'
        return url;
    }

    render(){return(
        <div>
        <div>{this.state.page}</div>
        <Container>
        <div style={{padding:"1em 1em", textAlign: "right"}}>

        <Card.Group itemsPerRow={3} stackable={true} doubling={true}>

        {this.state.data2.map(card=>(
        <Card href="#">
    <Image src={this.genurl(card.isbn)} wrapped ui={false} />
    <Card.Content>
      <Card.Header>{card.title}</Card.Header>
      <Card.Meta>
        <span className='date'>Author:{card.author}</span>
      </Card.Meta>
      <Card.Content >
      <Rating icon='star' defaultRating={card.avgrating} maxRating={5} />
    </Card.Content>
      <Card.Description>
        {card.avgrating} Avg rating, {card.totalratings} total ratings.
      </Card.Description>
    </Card.Content>
    <Card.Content >
      <a>
        <Icon name='pencil alternate' />
        {card.reviews} Reviews
      </a>
    </Card.Content>
  </Card>
  ))}
  
  </Card.Group>
  
        </div>

        </Container>
        </div>
    )
}
}

export default bookitem

First of all Bookitem must starts with capitalized letter.首先 Bookitem 必须以大写字母开头。 So instead of <bookitem /> you must have <Bookitem/>.所以你必须有<Bookitem/>.而不是<bookitem /> >。

Now if you want to change state of a react component from another component, you have to pass a function from parent to child which will be called when you want to change the state.现在,如果您想从另一个组件更改一个反应组件的 state,您必须将 function 从父级传递给子级,当您想要更改 Z9ED39E2EA931586B6A985A6942EF573E 时将调用它。 For example例如

const Compoent1 = () => { 
  const [state, setState] = useState(value)
  .....
  return <Component2 changeState={setState} />
}

The problem is that you are not rendering the bookitem component at all.问题是您根本没有渲染bookitem组件。 You have to manage the state of your activePage , pass it to the bookitem and actually render this component.您必须管理activePage的 state ,将其传递给bookitem并实际渲染此组件。

import React, { useState } from "react";
import { Pagination, Container } from "semantic-ui-react";
import BookItem from "./Book_item";

const PaginationI = () => {
  const [activePage, setActivePage] = useState(0); // manage the state of activePage

  function PageChange(event, data) {
    setActivePage(data.activePage); // update the state in event handler
  }

  return (
    <Container style={{ textAlign: "center", padding: "4rem" }}>
      <BookItem page={activePage} /> {/* render your component */}
      <Pagination
        defaultActivePage={5}
        totalPages={10}
        onPageChange={PageChange} /> {/* pass event handler */}
    </Container>
  );
};

export default PaginationI;

Also you would have to rename the bookitem component due to collision with HTML tags like this此外,由于与 HTML 标签发生冲突,您必须重命名bookitem组件

import React from "react";

class BookItem extends Component {
  constructor(props) {
    super(props);

    this.state = {
      counter: 0,
      page: 0,
      data2: [],
    };
  }

  componentWillMount() {
    console.log(this.props.page);
    axios.get("/books/" + this.state.page).then((res) => {
      console.log(res.data);
      this.setState({ data2: res.data });
    });
    console.log("aa");
    console.log(this.state.data2);
  }

  genurl(isbn) {
    console.log(isbn);
    let url = "http://covers.openlibrary.org/b/isbn/" + isbn + "-L.jpg";
    return url;
  }

  render() {
    return (
      <div>
        <div>{this.state.page}</div>
        <Container>
          <div style={{ padding: "1em 1em", textAlign: "right" }}>
            <Card.Group itemsPerRow={3} stackable={true} doubling={true}>
              {this.state.data2.map((card) => (
                <Card href="#">
                  <Image src={this.genurl(card.isbn)} wrapped ui={false} />
                  <Card.Content>
                    <Card.Header>{card.title}</Card.Header>
                    <Card.Meta>
                      <span className="date">Author:{card.author}</span>
                    </Card.Meta>
                    <Card.Content>
                      <Rating
                        icon="star"
                        defaultRating={card.avgrating}
                        maxRating={5}
                      />
                    </Card.Content>
                    <Card.Description>
                      {card.avgrating} Avg rating, {card.totalratings} total
                      ratings.
                    </Card.Description>
                  </Card.Content>
                  <Card.Content>
                    <a>
                      <Icon name="pencil alternate" />
                      {card.reviews} Reviews
                    </a>
                  </Card.Content>
                </Card>
              ))}
            </Card.Group>
          </div>
        </Container>
      </div>
    );
  }
}

export default BookItem;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React - 如何从另一个组件更改组件内的 state? - React - how to change state within component from another component? React - 从另一个子组件更改子组件中的状态 - React - Change state in child component from another child component 如何在 React Native 中从另一个功能组件更改一个功能组件的状态? - How to change state of one function component from another function component in React Native? 如何在本机反应中从不同组件更改另一个组件的 state? - How do I change state of another component from different component in react native? 如何使用 React 中另一个组件的按钮 function 在组件中调用更改 state? - How to call a change a state in a component using a button function from another component In React? 如何将 state 从子组件发送到 React 中的另一个组件 - How to send state from Child component to another component in React 如何使用 React 将状态从一个组件挂钩到另一个组件 - How to use React hooks state from one component to another Component 从 React 中的另一个组件更新组件的 state - Updating state of a component from another component in React 如何从不同的组件更改反应组件的 state? - How do you change state of a react component from a different component? 从另一个组件更改 class 组件 state - Change class component state from another component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM