【问题标题】:ReactJs: Passing url param to outside functionsReactJs:将 url 参数传递给外部函数
【发布时间】:2018-02-11 01:30:26
【问题描述】:

我正在使用 redux 开发同构反应应用程序。我在将 url 参数传递给调度 redux 操作的函数时遇到问题。

class SingleMovie extends Component { 
    componentDidMount(){
        console.log(this.props.match.params.id); // i can access the id here
    } 
     ..... 
}

function mapStateToProps(state){
    return {movie:state.movie};
}


function loadData(store, id){  //<--how do i get the id parameter 
    return store.dispatch(fetchMovie(id)); //<--so i can pass it here 
}

export default {
loadData,
component: connect(mapStateToProps,{fetchMovie})(SingleMovie)
};

我尝试了什么:

(1) 在 React 组件之外声明一个常量

let id = "";

class SingleMovie extends Component { 
...

(2) 尝试用id分配全局变量

componentDidMount(){
    id= this.props.match.params.id;
}  

id 总是未定义。

【问题讨论】:

    标签: javascript reactjs npm react-redux


    【解决方案1】:

    先将id参数保存到state中,然后使用setState的回调函数来调度fetchMovie动作。

    class SingleMovie extends Component { 
      constructor(){
        this.state = {
          id: ""
        }
      }
      componentDidMount(){
        //console.log(this.props.match.params.id);
        this.getMovieId(this.props.match.params.id);
      }
      getMovieId = (movieId) => {
        this.setState({
          id: movieId
        }, () => {
          this.loadData();
        })
      }
      loadData = (store) => {
        store.dispatch(fetchMovie(this.state.id));
      }
      render(){
        return(
          ...
        )
      }
    

    【讨论】:

    • 谢谢,但现在我收到一条错误消息:ReferenceError: store is not defined。我如何让回调可以访问商店。
    • 你的意思是 store.dispatch(getMovieId(this.state.id));或 store.dispatch(fetchMovie(this.state.id));..我收到一个新错误说 TypeError: Cannot read property 'dispatch' of undefined
    • fetchMovie 就是我说的。
    猜你喜欢
    • 2021-09-21
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 2013-01-13
    • 2018-09-26
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    相关资源
    最近更新 更多