Redux.js, Webpack.js, index.html - моя функция рендеринга не обновляет DOM index.html - PullRequest
0 голосов
/ 09 июня 2018

Я сейчас работаю над веб-пакетом.По причине, которую я не понимаю, мои функции приведения не загружают DOM.Тем не менее, консоль Google возвращает хорошие результаты моих функций.

Все выглядит хорошо, но в коде есть что-то, что создает эту ошибку: мой DOM не отображает li моей функции рендеринга рендеринга.

Итак, я проверил конфигурацию Webpackи поток данных index.html, все кажется великолепным.Что мне не хватает, если таковые имеются?

здесь мой webpack.config.js:

const webpack = require("webpack");
const path = require("path");
module.exports= {
  mode: "development",
    entry : "./src/index.js",
    output: {
      path : path.resolve(__dirname, 'dist'),
       publicPath: 'dist',
        filename : "main.js"
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin()
    ],
    //Loaders   tell    webpack what    to  do  with    the entry   file
    module:{
        rules: [{
            test: /.(js|jsx)$/,
            loader: "babel-loader",
            exclude : /node_modules/
        }]

    },
    devServer :{
      publicPath: "/",
      contentBase: path.join(__dirname, "dist"),
      hot: true
    }
}

здесь мой index.js:

import {
  createPost,
  editPost,
  setFilter
} from './actions';
import {
  appReducer
} from "./reducers.js";
import {
  createStore
} from "redux";

let store = createStore(appReducer)
const unsubscribe = store.subscribe(() => {
  console.log("state: ", store.getState())
})
store.dispatch(createPost("Brian", "Hello world =D !"));

const root = document.getElementById('root');
const render = () => {
root.innerHTML = ''
const { posts } = store.getState()
posts.forEach((post, index) => {
const item = document.createElement('li')
item.addEventListener('click', () =>
store.dispatch(editPost(index, post.text + '!'))
)
const text = document.createTextNode(post.user + ' - ' + post.text)
item.appendChild(text)
root.appendChild(item)

})
  const stopRender = store.subscribe(render)
}


store.dispatch(createPost("user1", "text1"))
store.dispatch(createPost("user2", "text2"))

здесь мой reducer.js:

import {
  CREATE_POST,
  EDIT_POST,
  SET_FILTER
} from "./actionTypes";
import {combineReducers} from "redux";
export function postsReducer(state = [], action) {
  switch (action.type) {

    case CREATE_POST:
      {
        const {
          type,
          ...post
        } = action

        return [...state, post]
      }

    case EDIT_POST:
      {
        const {
          type,
          id,
          ...newPost
        } = action
        return state.map((oldPost, index) =>
          action.id === index ? { ...oldPost,
            ...newPost
          } : oldPost)

      }

    default:
      return state
  }


}

export function filterReducer(state = "all", action) {
  if (action.type === SET_FILTER) {
    return action.filter
  } else {
    return state
  }

}

export const appReducer = combineReducers({
post : postsReducer,
filter : filterReducer
})

вот мой index.html:

<!DOCTYPE   html>
<html>
        <head>
                <meta   charset="utf-8">
                <title>Learning Redux</title>

        </head>
        <body>
                <div id="root"></div>
                <script src="main.js"></script>

        </body>
</html>

Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...