在React组件外部更新

时间:2020-03-28 21:37:21

标签: reactjs

我有一个用于在页面某处显示新闻的组件。您可以为新闻评分(给它加星标)。

我在另一个显示新闻的地方有另一个组件。在该部分中,您还可以对新闻进行评分。我想在News中投票后更新<SomeComponentWhereNewsAreDisplayed />组件(将其渲染)。有办法吗?

一些伪代码:

class SomeComponentWhereNewsAreDisplayed extends React.Component
{
    voteAndUpdateNewsComponent() {
         updateNewsComponent()
    }
    render() {
        return <div>
            ...
            <some functionality that allows to give a star to news onClick={this.voteAndUpdateNewsComponent}>
            ...
        </div>
    }
}

class News extends React.Component
{
    componentDidMount() {
        //..ajax request to get ratings, or taking it from localStorage, etc..
    }

    render() {
        return <div>
            {this.state.ratings.map(rating => { return <span>{rating.stars}</span>})
        </div>
    }
};

3 个答案:

答案 0 :(得分:0)

您好,您可以使用状态管理(例如Redux或Context)来解决此问题。

答案 1 :(得分:0)

通常来说,如果两个React组件不属于同一组件层次结构,则它们不能交换数据。有很多技巧可以解决这些问题,但理想情况下,您希望将它们置于相同的层次结构中并交换道具和回调。

如果您不想这样做,您仍然可以使用Redux将状态管理拉出层次结构:https://react-redux.js.org/api/connect

答案 2 :(得分:0)

您不需要为此使用状态容器。将一个函数从SomeComponentWhereNewsAreDisplayed传递到新闻,该函数更新SomeComponentWhereNewsAreDisplayed的状态,并附加到新闻中星级评分的点击处理程序。这会使您的父级(SomeComponentWhereNewsAreDisplayed)及其子级重新呈现。