调用从已道具

问题描述:

我想模块化很大成分,所以我可以重复使用它的一些零件传递函数的setState。调用从已道具

两个时间列表呈现上,我可以做的操作:更新我的模态状态,以便关闭,然后启动与服务器调用一个终极版的动作。

所以我想通过定义自定义行为的函数:

var handleSubmit = (name, description, author) => { 

    if (inputsValidated(name, description)) { 
     this.setState({ addingNewProject: false, errorMessage: '' }); 

     var payload = { name: name, date: new Date(), description: description, author: author}, 
      routeToPushAfter = `/app/users/${author._id || 'notsigned'}`, 
      serverRoute = allRoutes.projectURL, 
      type = 'project' 

      this.props.postData(payload, routeToPushAfter, serverRoute, type); 
    } 

    else { 
     this.setState({ errorMessage: 'Please fill out form' }); 
    } 
} 

那么这个函数传递给该组件。

render() { 
    return (
     <div style={main}> 
      <DynamicList {...this.props} /> 
      <DynamicList {...this.props} handleSubmit={handleSubmit} handleDelete={handleDelete} /> 
     </div> 
    ); 
} 

问题是:this.setState绑定到父组件。我怎么能传递一个函数,我可以修改本地状态(不使用Redux)。

感谢您的任何意见!

+1

可以使用[高顺序组件(https://reactjs.org/docs/higher-order-components。 HTML) –

+0

而不是保持错误信息的状态,你应该传递错误信息到列表中作为道具的一部分。是的,这是HOC的概念。 – robbymurphy

+0

我正在阅读HOC,谢谢。 @robbymurphy,这将解决errormessage的,但不是addingNewProject布尔,我需要的模式打开和关闭。 – DSz

您可以将功能结合到DynamicList的构造函数里面的成分:

constructor(props) { 
    super(props); 
    if (this.props.handleSubmit) { 
    this.handleSubmit = this.props.handleSubmit.bind(this); 
    } 
} 
+1

这是一个创可贴。它使得DynamicList和它的容器之间产生了紧密的耦合。该DynamicList应该是“愚蠢的”,简单地接受指定它应该如何,而不是渲染处理自己的错误状态的道具。特别是因为产生错误的函数在DynamicList组件之外。 – robbymurphy