简体   繁体   English

React - 当父级更改时更新子组件中的 state

[英]React - update state in the child component when parent changes

I have a simple application with two react components:我有一个包含两个反应组件的简单应用程序:

  1. vacancies.jsx - lists vacancies vacancies.jsx - 列出空缺职位
  2. counter.jsx - shows the number of vacancies from vacancies.jsx counter.jsx - 显示来自 vacancies.jsx 的空缺数量

When the application loads the counter shows the correct number of vacancies, but as I start adding/deleting vacancies in vacancies.jsx the count stays the same.当应用程序加载时,计数器显示正确的空缺数量,但是当我开始在 vacancies.jsx 中添加/删除空缺时,计数保持不变。

vacancies.jsx:职位空缺.jsx:

export class Vacancy extends React.Component {

    constructor(props) {

        super(props);

        this.state = { vacancies: [], loading: true, title:"" };

        fetch('/api/Vacancy/Vacancies')
            .then(response => response.json())
            .then(data => {
                this.setState({ vacancies: data, loading: false });
            });
    }

    delete(id) {

        var vacancies = this.state.vacancies;

        this.setState(
            {
                vacancies: this.state.vacancies.filter((v) => {
                    return (v.id != id);
                })
            });

    }

    loadVacancies(vacancies) {
        return (
            <table className='table table-striped'>
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Min Salary</th>
                        <th>Max Salary</th>
                    </tr>
                </thead>
                <tbody>
                    {vacancies.map(v =>
                        <tr key={v.id}>
                            <td>{v.title}</td>
                            <td>{v.currency} {v.minSalary}</td>
                            <td>{v.currency} {v.maxSalary}</td>
                            <td>
                                <a href="#" onClick={(id) => this.delete(v.id)}>Delete</a>
                            </td>
                        </tr>
                    )}
                </tbody>
            </table>
        );
    }

    render() {

        let contents = this.state.loading
            ? <p><em>Loading...</em></p>
            : this.loadVacancies(this.state.vacancies);

        return (
            <div>
                {contents}
            </div>
        );
    }
}

const containerElement = document.getElementById('content');
ReactDOM.render(<Vacancy />, containerElement);

counter.jsx计数器.jsx

import { Vacancy } from "./vacancies";

export class Counter extends Vacancy {

    constructor(props) {

        super(props);
    }

    render() {

        return (
            <div>
                <h1>Items:{this.state.vacancies.length}</h1>
            </div>
        );
    }
}

ReactDOM.render(<Counter />, document.getElementById('counter'));

UI:用户界面: 在此处输入图像描述

According to the react team, they recommend using composition instead of inheritance:根据反应团队的说法,他们建议使用组合而不是 inheritance:

React has a powerful composition model, and we recommend using composition instead of inheritance to reuse code between components. React 有一个强大的组合 model,我们建议使用组合而不是 inheritance 来重用组件之间的代码。

And

At Facebook, we use React in thousands of components, and we haven't found any use cases where we would recommend creating component inheritance hierarchies.在 Facebook 中,我们在数千个组件中使用 React,我们还没有发现任何建议创建组件 inheritance 层次结构的用例。

https://reactjs.org/docs/composition-vs-inheritance.html https://reactjs.org/docs/composition-vs-inheritance.html

So based on your code, recreate your Counter component like this:因此,根据您的代码,重新创建您的Counter组件,如下所示:

export const Counter = props => {
    return (
        <div>Items: {props.items}</div>
    );
};

Then just change your Vacancies component including your new Counter component there:然后只需更改您的Vacancies组件,包括您的新Counter组件:

loadVacancies(vacancies) {
    return (

        <Counter items={this.state.vacancies.length} />

        <table className='table table-striped'>
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Min Salary</th>
                    <th>Max Salary</th>
                </tr>
            </thead>
            <tbody>
                {vacancies.map(v =>
                    <tr key={v.id}>
                        <td>{v.title}</td>
                        <td>{v.currency} {v.minSalary}</td>
                        <td>{v.currency} {v.maxSalary}</td>
                        <td>
                            <a href="#" onClick={(id) => this.delete(v.id)}>Delete</a>
                        </td>
                    </tr>
                )}
            </tbody>
        </table>
    );
}

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

相关问题 ReactJS-当父组件状态改变时更新子组件中的状态 - Reactjs - Update state in child component when parent componend state changes 当父状态更改时,强制子组件更新 - Force a child component to update when the parent state changes 当父组件更新时,React阻止子组件中的更改状态 - React prevent change state in child component when parent component update 当 React 中的父状态发生变化时重新渲染子组件 - Rerendering child component when parent state changes in React React - 当父 state 更改时更新子级,而不使用 componentWillReceiveProps()? - React - update child when parent state changes, without using componentWillReceiveProps()? 父组件更改时更新子组件 - update child component when parent component changes 父 state 更改时子组件不更新 - Child component not updating when parent state changes 在React中将状态从子组件更新为父组件 - Update the state from child to parent component in React React/Redux - 从子组件更新父组件中的状态 - React/Redux - Update state in parent component from child component 当提供程序组件父状态更改时,为什么无法更新子组件中的值(使用react上下文)? - Why can't update a value in a child component (with react context) when a provider component parent state change?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM