【问题标题】:Axios auto refresh with ReactAxios 使用 React 自动刷新
【发布时间】:2019-01-07 13:54:43
【问题描述】:

我从 React 慢慢开始我的冒险,从几天开始就坐在这个问题上,想学习 axios 所以我正在创建基于 Json 服务器包的电影库。一切都很好,只是我无法在添加编辑或删除新电影等每次操作后进行自动刷新。我知道我必须以某种方式将函数 getMovie 传递给 editMovie、deleteMovie 和 addMovie 部分,但我完全不知道如何。我将 getMovie 放入函数并将其传递给 componentDidMount 以在一开始就启动它,但我不知道如何将它传递给表单组件以将其放入编辑/删除/添加函数中。我试图通过导出功能做到这一点,但没有成功。可能我必须通过道具来做到这一点,但它也不想为我工作:(我会非常感谢任何帮助,因为我没有想法。

表单组件

class Form extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            name: '',
            type: '',
            description: '',
            id: '',
            movies: [],
            errors: "",
        }
    }


    handleChangeOne = e => {
        this.setState({
            name: e.target.value
        })
    }
    handleChangeTwo = e => {
        this.setState({
            type: e.target.value
        })
    }
    handleChangeThree = e => {
        this.setState({
            description: e.target.value
        })
    }


    handleSubmit = e => {
        e.preventDefault()
        const url = `http://localhost:3000/movies/`;
        if (this.state.name != "" && this.state.type != "" && this.state.description != "") {
            axios
                .post(url, {
                    name: this.state.name,
                    type: this.state.type,
                    description: this.state.description,
                    id: this.state.id
                })
                .then(res => {
                    // console.log(res);
                    // console.log(res.data);
                    this.setState({
                        movies: [this.state.name, this.state.type, this.state.description, this.state.id]
                    })
                })
        }
        else {
            this.setState({
                errors:"Please, Fill all forms above"
            })
        }
    }

    handleRemove = e => {
        // const url = `http://localhost:3000/movies/`;
        const url = `http://localhost:3000/movies/${e.id}`;
        axios
            .delete(url)
            .then(res => {
                console.log(res.data);
            })
            .catch((err) => {
                console.log(err);
            })
    }

    editMovie = e => {
        if (this.state.name != "" && this.state.type != "" && this.state.description != "") {
            const url = `http://localhost:3000/movies/${e.id}`;
            axios
                .put(url, {
                    name: this.state.name,
                    type: this.state.type,
                    description: this.state.description,
                })
                .then(res => {
                    console.log(res.data);
                })
                .catch((err) => {
                    console.log(err);
                })
        }
        else {
            this.setState({
                errors:"Please, Fill all forms to edit movie"
            })
        }
    }



    render() {


        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <input type="text" placeholder="Movie" onChange={this.handleChangeOne}/>
                    <input type="text" placeholder="Type of movie" onChange={this.handleChangeTwo}/>
                    <textarea placeholder="Description of the movie"
                              onChange={this.handleChangeThree}></textarea>
                    <input id="addMovie" type="submit" value="Add movie" ></input>
                    <p>{this.state.errors}</p>
                </form>
                <List removeClick={this.handleRemove} editClick={this.editMovie}/>
            </div>
        )
    }
}

列表组件

class List extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            movies: [],
        }
    }

    componentDidMount() {
        this.getMovie()

    }
     getMovie = () => {
        const url = `http://localhost:3000/movies`;
        console.log(url);
        axios
            .get(url)
            .then(res => {
                console.log(res.data);
                const movies = res.data;
                this.setState({
                    movies: movies,
                })
            })
            .catch((err) => {
                console.log(err);
            })
        }
    // }




    editMovie = (event, e) => {
        event.preventDefault();
        console.log("it works with edit!");
        if (typeof this.props.editClick === "function") {
            this.props.editClick(e)
        } else {
            console.log("Doesn't work with edit");
        }
    }


    removeMovie = (event, e) => {
        event.preventDefault();
        console.log("it works with remove!");
        if (typeof this.props.removeClick === "function") {
            this.props.removeClick(e)
        } else {
            console.log("Doesn't work with remove");
        }
    }


    render() {

        return (
            <div className="movieList">
                {this.state.movies.map(e =>
                    <ul>
                        <li data-id={e.id} onClick={event => this.editMovie(event, e)}>
                            Title: {e.name}
                        </li>
                        <li data-id={e.id} onClick={event => this.editMovie(event, e)}>
                            Type: {e.type}
                        </li>
                        <li data-id={e.id} onClick={event => this.editMovie(event, e)}>
                            Description: {e.description}
                        </li>
                        <button className="removeMovie" type="submit" onClick={event => this.removeMovie(event, e)}>Delete</button>
                    </ul>)}
            </div>
        )
    }
}

【问题讨论】:

    标签: javascript json reactjs axios


    【解决方案1】:

    它不会刷新,因为它只在组件完全加载后被调用一次。您需要的是在更新后执行的触发器。

    对于这些,React 公开了一些生命周期方法。

    您应该将 getMovie() 方法移动到 componentWillReceiveProps()componentDidUpdate()

    如果你使用的是最新的 react 版本,你应该使用getDerivedStateFromProps()

    这三个方法将在您每次更新状态时执行。但是,这些方法在不同的用例中很有用(您必须自己决定)

    希望这会有所帮助;)

    【讨论】:

    • 嘿,谢谢你的回答:) 实际上它或多或少地工作得很好,我的意思是我使用了 componentDidUpdate() 因为那是唯一的工作方法(稍后我会阅读更多关于其他两个的信息,因为我第一次听说它们),但正如我在控制台日志中看到的那样,它每秒都在刷新。我之前用 setInterval 做过类似的事情,效果是一样的,但我想这是不必要的资源浪费。我是初学者所以即使没有采取任何行动也可以保持刷新吗?或者它应该在我执行某些操作时启动?
    • 每次更新后都会触发此方法。您必须在其中实际放置 if 条件,以检查您实际想要获取哪些条件。有些可能是不必要的
    • 嗯,我明白了,但在表单组件中,我尝试设置componentDidUpdate() { if (this.handleRemove() || this.editMovie()) { this.getMovie() } 之类的条件,作为回报,我收到错误无法读取未定义的属性“preventDefault”
    • 函数如何用作条件?你不应该为每个处理程序分配一个变量吗?像isRemovedButtonClicked 的条件一样?
    • 嗯,这看起来很简单,可能是这样,但我想这会让我心脏病发作,很抱歉朋友有很多愚蠢的问题,但我真的很想最终处理这个 React.. 无论如何,如果我记得很清楚的话js 我可以做let removeMovie = (event,e) =&gt; {...} 但在这里它显示错误是不可能的。但这是你的意思吗?以这种方式或多或少地分配变量只是纠正一个?我试着做var isRemovedButtonClicked = removeMovie(events) =&gt;{...} 然后我会把它放到componentDidUpdate() { if (isRemovedButtonClicked === true) { this.getMovie()}
    猜你喜欢
    • 2019-08-25
    • 2021-08-06
    • 2021-12-17
    • 1970-01-01
    • 2019-08-07
    • 2022-06-23
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多