javascript - 数据库插入后刷新 View React Redux

标签 javascript reactjs redux

我正在使用 React/Redux 创建一个应用程序,我已成功创建一个操作/ reducer 以将记录插入我的数据库 - 这是 ForerunnerDB

到目前为止我的代码如下所示:

页面

class Projects extends Component {
  componentWillMount() {
    this.props.FetchProjects();
  }

  renderProjects() {
    return this.props.projects.map( ( project ) => {
      return (
        <li key={ project._id } >
          <Link to={ `/pages/${project._id}` } >{ project.title } { project.timestamp.toString() }</Link>
        </li>
      );
    });
  }

  render() {
    return (
      <div className="projects container">
        <div className="projects">
          <ul>
            <li>
              <CreateNewProject />
            </li>
            { this.renderProjects() }
          </ul>
        </div>
      </div>
    );
  }
}

function mapStateToProps( state ) {
  return {
    projects: state.projects.all
  }
}

export default connect( mapStateToProps, actions )( Projects );

我正在使用 <CreateNewProject />组件插入记录和 renderProjects()获取项目列表的方法。如果我刷新页面,项目就会呈现得很好,但我无法弄清楚如何在记录自动插入数据库时​​更新列表。

有人能帮我指出正确的方向吗?

提前非常感谢。

编辑

项目行动

// Fetch existing projects
export function FetchProjects() {
  return ( dispatch ) => {
    // Load projects collection
    projectsCollection.load( ( err ) => {
      // if there are no errors
      if( !err ) {
        // Set up action payload
        const projects = projectsCollection.find();
        // Dispatch the action using the above
        dispatch({
          type: FETCH_PROJECTS,
          payload: projects
        });
      // If there's an error loading the projects collection
      } else {
        //Log the error
        console.log( `ERR! ${err}` );
      }
    });
  }
}
// Create new project
export function CreateProject( { projectName } ) {
  return ( dispatch ) => {
    // Load projects collection
    projectsCollection.load( ( err ) => {
      // If there are no errors
      if( !err ) {
        // Set up action payload
        // Insert record into projects collection
        const projectCreate = projectsCollection.insert({
          title: projectName,
          timestamp: fdb.make( new Date() )
        }, ( result ) => {
          // If insertion is successful
          if( result.inserted.length ) {
            // Save the projects collection (persisted to local storage)
            projectsCollection.save( ( err ) => {
              // If there are no errors
              if( !err ) {
                console.log( result.inserted[0] )
              } else {
                // Log the error
                console.log( `ERR! ${err}` );
              }
            });
          } else {
            // Log the failed insertion
            console.log( `ERR! ${result.failed}` );
          }
        });
        // Dispatch the action using the above
        dispatch({
          type: CREATE_PROJECT,
          payload: projectCreate
        });
      // If there's an error loading the projects collection
      } else {
        // Log the error
        console.log( `ERR! ${err}` );
      }
    });
  }
}

FETCH_PROJECTS reducer

// Import dependencies
import { FETCH_PROJECTS } from '../../actions/types';

// Set inital state
const INITIAL_STATE = { all: [] }

export default function( state = INITIAL_STATE, action ) {
  switch( action.type ) {
    case FETCH_PROJECTS:
      return { ...state, all: action.payload }
  }

  return state;
}

CREATE_PROJECTS reducer

import { CREATE_PROJECT } from '../../actions/types';

export default function( state = {}, action ) {
  switch( action.type ) {
    case CREATE_PROJECT:
      return { ...state, projects: action.payload }
  }

  return state;
}

最佳答案

您应该将一个操作传递给 CreateNewProject 组件。这样您就可以触发操作以从组件插入新记录。然后该操作将通过 reducer 更新存储。一旦商店更新,它将触发项目组件的更新,因为它将其 Prop 之一映射到项目商店。

编辑 - 有问题提供的附加代码揭示了更多内容:

我注意到可能导致该问题的原因。在 PROJECTS 操作中,函数 CreateProject 存在同步性问题。您尝试创建 projectCreate ,然后将其作为操作中的有效负载传递。问题在于 projectsCollection.insert() 是一个异步函数(由回调指示)。这意味着 dispatch() 调用的 projectCreate 具有未定义的值。

我建议将 dispatch() 调用放在最后一个回调 projectsCollection.save() 中:

      projectsCollection.save( ( err ) => {
          // If there are no errors
          if( !err ) {
            console.log( result.inserted[0] )
            // dispatch the successful result
            dispatch({
              type: CREATE_PROJECT,
              payload: result.inserted[0]
            });
          } 
          ...
       }

关于javascript - 数据库插入后刷新 View React Redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37301186/

相关文章:

javascript - 空数组是否严格等于 JavaScript 中的任何内容?

javascript - 在 Twitter 上获取/用户/显示/返回错误 :400 and Error:404 (AJAX)

javascript - Warning : setState(. ..): Can only update a mounted or mounting component on a new reactjs app

javascript - 使用子组件添加应用程序状态?

redux - 为什么将 mapDispatchToProps 和 mapStateToProps 的方法分开?

react-native - react 导航 : change tabNavigator style based on redux store

javascript - 获取存储在隐藏输入中的对象数组

javascript - 无法在 jQueryUI 对话框上执行 javascript 函数

mongodb - meteor Mup错误fbjs不变

Javascript const 在 chrome 开发控制台中显示为未定义而不是未定义