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

时间:2020-06-22 11:15:42

标签: javascript reactjs

我看到了数十个示例,但在我的情况下它们不起作用,我想更新“ bookitem”组件中的page变量并将其重新呈现。使用会产生错误“期望分配或函数调用,而看到一个表达式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

2 个答案:

答案 0 :(得分:0)

首先,Bookitem必须以大写字母开头。因此,您必须拥有li $v0,10 syscall

来代替<bookitem />

现在,如果要从另一个组件更改React组件的状态,则必须将一个函数从父级传递到子级,当您要更改状态时将调用该函数。例如

<Bookitem/>.

答案 1 :(得分:0)

问题是您根本没有渲染bookitem组件。您必须管理activePage的状态,将其传递给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;

由于与这样的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;