【问题标题】:How can I add delete buttons to clear whole state and remove specific state that .map function turns?如何添加删除按钮以清除整个状态并删除 .map 函数变为的特定状态?
【发布时间】:2019-08-24 09:34:38
【问题描述】:

我尝试初始化数组以删除其中的所有元素,但它不起作用。

clearAll(){
   this.setState({
      posts: []
   })
}

componentDidMount() {
    axios.get('https://jsonplaceholder.typicode.com/posts')
        .then(Response => {
        console.log(Response)
        this.setState({posts:Response.data})
        })
        .catch(error => {
        console.log(error)
        this.setState({errorMsg: "Error retreiving data !"})
        })
    }

render() {
    const {posts , errorMsg} = this.state
    return (
        <div>
            Post List Here.
            {
                posts.length ?
                posts.map(post => <div> key={post.id}>{post.title}</div>) :
                null
            }
            { errorMsg ? <div>{errorMsg}</div> : null}
        </div>
    );
}

我检查了购物车并观看了有关此的视频,以找到删除特定状态但它不再起作用的按钮。有人可以给我一个按钮或想法吗?我需要 2 个按钮来删除来自 .json 的所有状态并删除其中特定的一个。

【问题讨论】:

  • 你永远不会调用 clearAll 函数。可能是一个绑定问题:onClick={()=&gt;this.clearAll()} 应该解决这个问题
  • 你的意思是删除一个特定的帖子和一个删除所有数据的帖子吗?

标签: javascript reactjs typescript react-redux react-router


【解决方案1】:

调用您的clearAll 函数删除所有帖子,

clearAll(){
   this.setState({
      posts: []
   })
}

removePost(postId){
  this.setState(state=>({posts: state.posts.filter(post=> post.id !== postId)})
}

删除特定帖子。内部调用post&lt;div/&gt;按钮onClick

render() {
const {posts , errorMsg} = this.state
return (
    <div>
        Post List Here.
        {
            posts.length ?
            posts.map(post => <div key={post.id}><div>{post.title}</div><button type="button" onClick={()=>this.removePost(post.id)}>Remove Post</button></div>) :
            null
        }
        { errorMsg ? <div>{errorMsg}</div> : null}
        <button type="button" onClick={()=>this.clearAll()}>Remove All Posts</button>
    </div>
);
}

【讨论】:

  • 非常感谢,但我能问点小事吗?当我执行该项目时,它显示“警告:列表中的每个孩子都应该有一个唯一的“关键”道具。”但我们已经给了他们钥匙。为什么会这样?
  • @Pensar Nada ,抱歉我错过了一些东西,只需将您的 key 道具从内部 &lt;div/&gt; 移动到外部 &lt;div/&gt;
  • 再次感谢您,我已经为此工作了很多天,我才意识到我已经找到了解决方案:D
【解决方案2】:

创建

 const initatialState={
posts:[],
errorMsg:''
}
when you want cleat ued 
clearAll=()=>{
this.setState({...initatialState})}

告诉我它是否在提交中起作用

【讨论】:

    猜你喜欢
    • 2015-06-24
    • 2013-07-22
    • 2017-09-19
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多