代码之家  ›  专栏  ›  技术社区  ›  Zoltan Kovacs

如何在不刷新页面的情况下显示发布的数据?

  •  0
  • Zoltan Kovacs  · 技术社区  · 7 年前

    我有一个简单的react应用程序,它可以获取数据并将数据发布到API。这是一个简单的图片分类库。

    第一步,我从API获取所有库。这很好。

    class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            galleries: [],
            isLoading: false,
            error: null,
        };
    }
    
    componentDidMount() {
        this.setState({ isLoading: true });
    
        fetch('http://.../gallery')
            .then((response) => response.json())
            .then((data)=>this.setState({galleries: data.galleries, isLoading: false}))
            .catch(error => this.setState({ error, isLoading: false}));
    }
    
    render() {
        const {galleries, isLoading, error} = this.state;
        if (error) {
            return <p>{error.message}</p>;
        }
    
        if (isLoading) {
            return <div className="loader-wrapper"><div className="loader"/></div>;
        }
    
        return (
            <div className="categories">
                { galleries.length > 0 ? galleries.map((gallery) => {
                    return (
                        <Card key={gallery.path}>
                            ...
                        </Card>
                    )}) : null
                }          
                <AddCategory/> 
            </div>
        );
    }
    }
    

    在下一步中,您可以创建新的库。

    class AddCategory extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modal: false,
            galleries: [],
            isLoading: false,
            error: null,
        };
    
        this.toggle = this.toggle.bind(this);
    
        this.handleClick = this.handleClick.bind(this);
    }
    
    toggle() {
        this.setState({
            modal: !this.state.modal
        });
    }
    
    handleClick(event) {
        event.preventDefault();
        this.setState({
            modal: !this.state.modal
        });
        this.setState({ isLoading: true });
        fetch('http://.../gallery', {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({"name": this.galleryName.value})
        })
            .then((response) => {
                if (response.ok) {
                    return response.json();
                } else {
                    throw new Error('Something went wrong ...')
                }
            })
            .then((data)=>this.setState({galleries: data.galleries, isLoading: false}))
            .catch(error => this.setState({ error, isLoading: false}));
    }
    
    render() {
        const {modal, isLoading, error} = this.state;
    
        if (error) {
            return <p>{error.message}</p>;
        }
    
        if (isLoading) {
            return <div className="loader-wrapper"><div className="loader"/></div>;
        }
    
        return (
            <Card className="add">
                <div className="link" onClick={this.toggle}>
                    <CardBody>
                        <CardTitle>Add gallery</CardTitle>
                    </CardBody>
                </div>
                <Modal isOpen={modal} toggle={this.toggle} className={this.props.className}>
                    <div className="modal-header">
                        ...
                    </div>
                    <ModalBody>
                        <form className="form-inline addCategoryForm">
                            <div className="group">
                                <input type="text" ref={(ref) => {this.galleryName = ref}} id="inputGalleryName" name="galleryName" required/>
                                <label>name of the gallery</label>
                            </div>
                            <Button onClick={this.handleClick} color="success">Add</Button>
                        </form>
                    </ModalBody>
                </Modal>
            </Card>
        );
    }
    }
    

    问题是,在我单击“添加”按钮后,页面上什么也没有发生,但在我刷新页面后,新的库就出现在列表中了。

    你知道为什么我只是在刷新页面后,而不是在单击“添加”按钮后立即获得新的库吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Kartal Erkoc    7 年前

    如果不刷新,则无法在列表中看到新库的原因是,主要组件(在本例中为 Home 组件不会重新呈现,因为其状态变量没有任何更改,所以不会更新页面。您对的使用 this.setState 收到响应后,来自 POST 方法使用 fetch ,仅更新和重新渲染子组件 AddCategory .

    在下面的组件上添加评论部分,以便 组件重新渲染。

    对于 组成部分

    class Home extends Component {
        constructor(props) {
            super(props);
            this.state = {
                galleries: [],
                isLoading: false,
                error: null,
            };
    
            // Add this method binding
            this.updateGalleries = this.updateGalleries.bind(this);
        }
    
        // Add this method
        updateGalleries = () => {
            this.setState({ isLoading: true });
            fetch('http://.../gallery')
            .then((response) => response.json())
            .then((data)=>this.setState({galleries: data.galleries, isLoading: false}))
            .catch(error => this.setState({ error, isLoading: false}));
        }
    
        componentDidMount() {
            ...
        }
    
        render() {
            ...
    
            return (
                <div className="categories">
                    ...  
                    /* Add updateGalleries funtion as props to AddCategory */
                    <AddCategory updateGalleries={this.updateGalleries}/> 
                </div>
            );
        }
    }
    

    对于 添加类别 组成部分

    class AddCategory extends Component {
        constructor(props) {
            ...
        }
    
        toggle() {
            ...
        }
    
        handleClick(event) {
            ...
            // edit this field after response.json()
            .then((data)=>{
                this.setState({galleries: data.galleries, isLoading: false})
                this.props.updateGalleries();
            })
            .catch(error => this.setState({ error, isLoading: false}));
        }
    
        render() {
            ...
        }
    }