首页 > 解决方案 > React - 链接重定向到项目但不刷新组件

问题描述

当我单击 StageItem 'Details' 时,URL 正在更改,但 Stage 组件不刷新数据。我试图使用 Switch 和 withRouter,但没有成功,因为我完全不知道如何在我的情况下使用它们。提前感谢您的回答。我的代码:

应用程序

class App extends Component {
  render() {
    return (
        <BrowserRouter>
          <div className="App">
            <Header/>
            <div className="container">
                <div className="row">
                    <Route path='/' component={InputContainer}/>
                    <Route path='/' component={() => <StagesList todos={this.props.todos}/>} />
                    <Route path='/:stage_id' render={(props) => <Stage {...props} todos={this.props.todos}/>} />
                </div>
            </div>
          </div>
        </BrowserRouter>
    );
  }
}

const mapStateToProps = state => {
    return {
        todos: state.todos
    };
};

const mapDispatchToProps = {};

export const AppContainer = connect(mapStateToProps, mapDispatchToProps)(App);

舞台物品

export const StageItem = ({ todo, id, handleRemoveTodo}) => {

    return(
        <li className="stage_item" key={id}><span onClick={() => handleRemoveTodo(id)}><FontAwesomeIcon className="fa" icon="trash" />&nbsp;{todo.tour} - {todo.duration.hours}:{String(todo.duration.minutes).padStart(2,"0")}:{String(todo.duration.seconds).padStart(2,"0")} - {todo.distance} km - {todo.avgSpeed} km/h - {todo.maxSpeed} km/h</span><Link to={'/'+todo.id}>Details</Link></li>
    )

};

阶段列表

export class StagesListC extends React.Component{

    render(){

        return(
            <div className="col-12 col-sm-12 col-md-12 col-lg-12">
                <SectionTitle title="Stage list"/>
                {this.props.todos.length>0 ?
                <ul className="todo-list">
                    {this.props.todos.map((todo) => <StageItem
                        key={todo.id}
                        id = {todo.id}
                        todo={todo}
                        handleRemoveTodo = {this.props.handleRemoveTodo}
                    />)}
                </ul>
                :
                <div>You have no stages</div>}
            </div>
        )
    }

}

const mapStateToProps = dispatch => bindActionCreators({
    handleRemoveTodo
}, dispatch)

const mapDispatchToProps = { handleRemoveTodo };

export const StagesList = connect(mapStateToProps, mapDispatchToProps)(StagesListC);

完整项目:链接

标签: reactjsreact-reduxreact-router

解决方案


如果您不想在路线上看到and ,则需要添加exact到路线中。/InputContainerStagesList:stage_id

<div className="row">
    <Route path='/' exact component={InputContainer}/>
    <Route path='/' exact component={() => <StagesList todos={this.props.todos}/>} />
    <Route path='/:stage_id' render={(props) => <Stage {...props} todos={this.props.todos}/>} />
</div>

Stage您的组件中还有一个错误。

todo.id是一个整数,但是stage_id是一个字符串。要修复它,您可以将两者都转换为字符串,例如

let stage = todos.filter((todo) => String(todo.id) === String(id));

升级版:

如果您想随时查看StageListStage组件,则需要修复Stage组件。组件仅在触发时Stage更新其state.stage值一次。componentDidMount所有后续更新都不会更新stage.stage值。您可以在道具更改时实现componentWillReceiveProps生命周期方法并更新值。stage.stage或者,您不要在方法中使用state.stageand 计算stagerender,如下所示:

class Stage extends React.Component {

    getStage = () => {
        const todos = this.props.todos || [];
        let id = this.props.match.params.stage_id;
        return todos.filter((todo) => String(todo.id) === String(id))[0];
    }

    render() {

        const stage = this.getStage();

        if (!stage) return null;

        return <div className="col-12 col-sm-12 col-md-12 col-lg-12">
            <SectionTitle title="Single stage"/>
            <div>Id: {stage.id}</div>
            <div>Distance: {stage.distance}</div>
            <div>Duration: {stage.duration.hours}:{String(stage.duration.minutes).padStart(2, "0")}:{String(stage.duration.seconds).padStart(2, "0")}</div>
            <div>Average speed: {stage.avgSpeed} km/h</div>
            <div>Max speed: {stage.maxSpeed} km/h</div>
        </div>
    }
}

推荐阅读