Redux状态更改后组件未重新呈现

时间:2018-09-27 21:12:06

标签: reactjs

我有一个包含以下代码的容器:

class QuoteContainer extends Component {

  //FETCH ALL QUOTES
  componentDidMount() {
    this.props.fetchQuotes();
    this.props.fillColorArr();
  }

  checkIfQuotesReady = () => {
    let quotesCheck = this.props.quotesArr.length > 0;
    return quotesCheck;
  }

  changeQuoteHandler = () => {
    let randomQuote = this.props.quotesArr[Math.floor(Math.random() * 100)];
    console.log(randomQuote);
    return randomQuote;
  }

  render() {

    let quotesReady = this.checkIfQuotesReady();

    return (
      <div className="wrapper">
        {quotesReady ? <Quote quote={this.changeQuoteHandler()}/> : null}
        <Button changeQuote={this.props.displayedQuotesCounter}/>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    quotesArr: state.quotes,
    counter: state.counter
  }
}

const mapDispatchToProps = dispatch => {
  return {
    fetchQuotes: () => {
      fetch('https://talaikis.com/api/quotes/')
        .then(response => response.json())
        .then(quotes => dispatch({type: actions.FETCH_QUOTES, fillArr: quotes}))
    },
    fillColorArr: () => dispatch({type: actions.GET_COLORS}),
    displayedQuotesCounter: () => dispatch({type: actions.COUNT_QUOTES})
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(QuoteContainer);
按钮上的

“ changeQuote”触发操作以更新已显示的报价计数(简单计数器)。随着计数器在Redux状态下发生变化,我希望Quote行:

{quotesReady ? <Quote quote={this.props.quotesArr[Math.floor(Math.random() * 100)}/> : null}

将重新呈现,因此新的随机报价将显示在屏幕上。 事实证明,我错了,我很好奇这可能是什么解决方案。请记住,Quote组件无权访问商店,但已获得了以其本地状态存储的随机报价。 这也是我的减速器:

import createColorArr from '../utils/colors';
import * as actions from './actions';

//CREATE COLORS ARRAY FROM OBJECT FILLED WITH COLORS
const colors = createColorArr(); //IS IT OK?

//INITIAL APPLICATION STATE
const initialState = {
  quotes: [],
  colors: [],
  shownQuotes: 1
}

//ROOT (AND THE ONLY ONE) REDUCER
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case actions.FETCH_QUOTES:
      return {
        ...state,
        quotes: state.quotes.concat(action.fillArr)
      };
    case actions.GET_COLORS:
      return {
        ...state,
        colors: state.colors.concat(colors)
      }
    case actions.COUNT_QUOTES:
      return{
        ...state,
        shownQuotes: state.shownQuotes + 1
      }
    default:
      return state;
  }
}

导出默认的减速器; 这是一个学习目的的项目,我没有在寻找可以在Quote组件中访问商店的解决方案。预先感谢!

1 个答案:

答案 0 :(得分:0)

根据您的问题,我理解的是更改按钮上的报价会触发一个操作来更新已显示的报价计数器,但不会显示已更新的计数。我说的对吗?

如果是这样,那么您必须在每次更新时执行一次操作,您需要再次触发获取计数操作,以查看显示的更新计数,否则不会显示。如果您不这样做,那么您只会看到前一个报价,而看不到最新的报价。

在更新报价操作调用之后的changeQuote中

     Do something like below for eg

     changeQuote = () => {
          this.props.updateCount();
          setTimeout(()=> {
                 this.props.getCount();
                 this.props.fetchCounts(); //whichever action fetches you the quote count
           }, 2000);
    }