Reactjs 从props写入本地状态

Reactjs 从props写入本地状态,reactjs,redux,react-redux,fetch,Reactjs,Redux,React Redux,Fetch,我知道这个问题很小,但我不能处理它,我需要你的帮助 我尝试了类似问题的所有解决方案,但对我来说都不起作用 底线是,当我挂载组件时,我运行fetch并从我的API获得一个文章列表,但这不适合我,因为我不会将它们保存在本地状态 此外,我对React的了解非常糟糕,我还有两个问题: 1) 当我浏览页面时,当我返回到文章页面时,结果的数量以算术级数重复,据我所知,这是我将文章保存在道具中的问题,但我需要将其保存在本地状态。 2) 我的第二个问题从此结束。我尝试了所有的方法,但是我不能做props.art

我知道这个问题很小,但我不能处理它,我需要你的帮助

我尝试了类似问题的所有解决方案,但对我来说都不起作用

底线是,当我挂载组件时,我运行fetch并从我的API获得一个文章列表,但这不适合我,因为我不会将它们保存在本地状态

此外,我对React的了解非常糟糕,我还有两个问题: 1) 当我浏览页面时,当我返回到文章页面时,结果的数量以算术级数重复,据我所知,这是我将文章保存在道具中的问题,但我需要将其保存在本地状态。 2) 我的第二个问题从此结束。我尝试了所有的方法,但是我不能做props.articles->state.articles,以便将来应用这个.state.articles.map

//行动

import {FETCH_ALL_ARTICLES} from "../constants";


export const fetchAllArticles = () => {
  return (dispatch) => {
    let headers = {"Content-Type": "application/json"};

  return fetch("/api/articles/", {headers, })
    .then(res => {
       if (res.status < 500) {
         return res.json().then(data => {
           return {status: res.status, data};
       })
       } else {
         console.log("Server Error!");
         throw res;
    }
  })
  .then(res => {
    if (res.status === 200) {
      return dispatch({type: FETCH_ALL_ARTICLES, articles: res.data});
    }
  })
}
};

您可以直接从render函数中的this.prop.articles渲染文章

import React, { Component } from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';

import {articles} from "../actions";


class Home extends Component {

componentDidMount() {
    this.props.fetchAllArticles()
};

render() {
    return (
        <div>
            <Link to='/notes'>Notes</Link>
            <h2>All articles</h2>
            <hr />
            <table>
                <tbody>
                    {this.props.articles.map((article, id) => (
                        <tr key={`article_${id}`}>
                            <td>{article.headline}</td>
                            <td>{article.description}</td>
                            <td>{article.created}</td>
                            <td>{article.author.username}</td>
                            <td>{article.image}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    )
  }
}

const mapStateToProps = state => {
   return {
      articles: state.articles,
   }
};

const mapDispatchToProps = dispatch => {
    return {
       fetchAllArticles: () => {
           dispatch(articles.fetchAllArticles())
       }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);
import React,{Component}来自'React';
从'react redux'导入{connect};
从'react router dom'导入{Link};
从“./行动”导入{物品};
类Home扩展组件{
componentDidMount(){
this.props.fetchAllArticles()
};
render(){
返回(
笔记
所有文章

{this.props.articles.map((article,id)=>( {文章标题} {文章说明} {article.created} {article.author.username} {article.image} ))} ) } } 常量mapStateToProps=状态=>{ 返回{ 文章:state.articles, } }; const mapDispatchToProps=调度=>{ 返回{ fetchAllarticle:()=>{ 分派(articles.fetchAllArticles()) } } }; 导出默认连接(mapStateToProps、mapDispatchToProps)(主页);
您可以直接从渲染功能中的this.prop.articles渲染文章

import React, { Component } from 'react';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';

import {articles} from "../actions";


class Home extends Component {

componentDidMount() {
    this.props.fetchAllArticles()
};

render() {
    return (
        <div>
            <Link to='/notes'>Notes</Link>
            <h2>All articles</h2>
            <hr />
            <table>
                <tbody>
                    {this.props.articles.map((article, id) => (
                        <tr key={`article_${id}`}>
                            <td>{article.headline}</td>
                            <td>{article.description}</td>
                            <td>{article.created}</td>
                            <td>{article.author.username}</td>
                            <td>{article.image}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    )
  }
}

const mapStateToProps = state => {
   return {
      articles: state.articles,
   }
};

const mapDispatchToProps = dispatch => {
    return {
       fetchAllArticles: () => {
           dispatch(articles.fetchAllArticles())
       }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);
import React,{Component}来自'React';
从'react redux'导入{connect};
从'react router dom'导入{Link};
从“./行动”导入{物品};
类Home扩展组件{
componentDidMount(){
this.props.fetchAllArticles()
};
render(){
返回(
笔记
所有文章

{this.props.articles.map((article,id)=>( {文章标题} {文章说明} {article.created} {article.author.username} {article.image} ))} ) } } 常量mapStateToProps=状态=>{ 返回{ 文章:state.articles, } }; const mapDispatchToProps=调度=>{ 返回{ fetchAllarticle:()=>{ 分派(articles.fetchAllArticles()) } } }; 导出默认连接(mapStateToProps、mapDispatchToProps)(主页);
您的问题不清楚,但我将尝试根据标题“从道具写信给当地州”进行解释

您可以利用以下组件生命周期来实现这一点

componentWillReceiveProps(nextProps) { 
  if (nextProps.articles) {
    this.setState({ articles: nextProps.articles });
  }
}
基本上,每当更新此组件时,此生命周期方法
componentWillReceiveProps
将在重新渲染之前被调用,因此我们可以在此处调用setState并将其保存到本地状态

当我返回到文章页面时,结果的数量以算术级数重复


如果正确操作减速器,则不会发生这种情况。例如,从API获取文章后,清除数组,然后只存储从API接收的值。当然,这一切都取决于你想要达到的目标。你的问题还不清楚,但我会根据标题“从道具写信给地方政府”来解释

您可以利用以下组件生命周期来实现这一点

componentWillReceiveProps(nextProps) { 
  if (nextProps.articles) {
    this.setState({ articles: nextProps.articles });
  }
}
基本上,每当更新此组件时,此生命周期方法
componentWillReceiveProps
将在重新渲染之前被调用,因此我们可以在此处调用setState并将其保存到本地状态

当我返回到文章页面时,结果的数量以算术级数重复


如果正确操作减速器,则不会发生这种情况。例如,从API获取文章后,清除数组,然后只存储从API接收的值。当然,这完全取决于您想要实现的目标,您的问题很短,但据我所知,您希望通过道具将数据从父组件传递到子组件,然后将它们存储到本地状态

为此,您需要将构造函数添加到子组件中,并将道具分配给state-like

import React,{Component} from 'react';
class ChildComponent extends Component{
  constructor(props){
    super(props);
    this.state={
      name: props.name,
      email: props.email      
    }
  }
  ..........
  // your child component logic

}
通过父组件传递数据,如

<ChildComponent name={this.state.name} email={this.state.email} /> 

您的问题很简短,但据我所知,您希望通过道具将数据从父组件传递到子组件,然后将其存储到本地状态

为此,您需要将构造函数添加到子组件中,并将道具分配给state-like

import React,{Component} from 'react';
class ChildComponent extends Component{
  constructor(props){
    super(props);
    this.state={
      name: props.name,
      email: props.email      
    }
  }
  ..........
  // your child component logic

}
通过父组件传递数据,如

<ChildComponent name={this.state.name} email={this.state.email} /> 

每次安装组件时,您都会获取所有文章。 获取所有文章时,将它们添加到现有的Redux状态:

return [...state, ...action.articles];
要解决此问题,您可以丢弃旧物品,而不是保留它们:

return [...action.articles];
或者,如果已提取文章,则可以避免提取:

componentDidMount() {
    if (!this.props.articles || this.props.articles.length === 0) {
        this.props.fetchAllArticles()
    }
};
你不需要对当地政府做任何事情。你的Redux状态是你唯一的真相来源。在中保留另一份数据副本