Skip to main content

Arrow Function

· One min read
Lex
Front End Engineer @ Baoxiaohe

SO,今天又踩坑了,箭头函数没写返回值,返回包含undefined的数组。谁让箭头函数可以自动return呢👼

getBleedLine(item: Array<any>, faceData: Array<any> = this.getFaceData()) {  let res = Array<any>();  let emptyArr = Array<any>();
  for (let i = 0; i < faceData.length; i++) {    if (faceData[i].name === item[0]) {      for (let k = 1; k < item.length - 1; k++) {        emptyArr.push(faceData[i].dlist()[item[k]]);      }      res = emptyArr.map(ele => {        ele.x += item[item.length - 1].x ? item[item.length - 1].x : 0;        ele.y += item[item.length - 1].y ? item[item.length - 1].y : 0;        // warn: undefined + number = NaN        ele.cx = item[item.length - 1].x ?ele.cx+ item[item.length - 1].x : ele.cx;        ele.cy = item[item.length - 1].y ?ele.cy+ item[item.length - 1].y : ele.cy;
        return ele;      });      // console.log(res);    }  }
  return res;}

Markdown Features in Docusaurus

· 2 min read
Lex
Front End Engineer @ Baoxiaohe

Hey,there is a test docs.

Tabs#

Tabs 组件 👇

This is an apple 🍎,may should call "爱疯"

Language Tabs#

不得不说的是,三种语言,Java 最呆(重)

function helloWorld() {  console.log("Hello, world!");}

Interactive code editor#

显示当前时间#

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

修改样式#

Code Blocks with JSX,U can change it then display reaction. 你可以尝试修改 style属性的值,然后查看发生了什么变化 🍳

Live Editor
Result
SyntaxError: Unexpected token (1:8)
1 : return ()
            ^

That's all

Extends in JavaScript

· One min read
Lex
Front End Engineer @ Baoxiaohe

Class in ES6#

ES6(May ES6,7...)新增了Class语法,似乎使得 JavaScript 能像 Java 一样使用继承语法了。

class Person{  constructor(name,age) {    this.name = name    this.age = age  }    running(){    console.log("yep,i am running")  }}
class Student extends Person{  constructor(name,age,sno) {    super(name,age);    this.sno = sno  }}

transform to ES5#

var Person = /*#__PURE__*/function () {  function Person(name, age) {    _classCallCheck(this, Person);
    this.name = name;    this.age = age;  }
  _createClass(Person, [{    key: "running",    value: function running() {      console.log("yep,i am running");    }  }]);
  return Person;}();
var Student = /*#__PURE__*/function (_Person) {  _inherits(Student, _Person);
  var _super = _createSuper(Student);
  function Student(name, age, sno) {    var _this;
    _classCallCheck(this, Student);
    _this = _super.call(this, name, age); // 通过 call 绑定 this     _this.sno = sno;    return _this;  }
  return Student;}(Person);

🕵️‍♂️

可以看到 子类 Student 通过调用 call 函数将父类构造函数中的 this 绑定为自身,相当于在自身调用

this.name = namethis.age = agethis.sno = sno

So,Class 语法本质上还是 function.

Function is a first-class citizen in JavaScript.

TodoMVC powered by Vue.js

· 2 min read
Lex
Front End Engineer @ Baoxiaohe

Source#

// Full spec-compliant TodoMVC with localStorage persistence// and hash-based routing in ~120 effective lines of JavaScript.
// localStorage persistenceconst STORAGE_KEY = "todos-vuejs-2.0";const todoStorage = {  fetch() {    const todos = JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]");    todos.forEach((todo, index) => {      todo.id = index;    });    todoStorage.uid = todos.length;    return todos;  },  save(todos) {    localStorage.setItem(STORAGE_KEY, JSON.stringify(todos));  },};
// visibility filtersconst filters = {  all(todos) {    return todos;  },  active(todos) {    return todos.filter((todo) => !todo.completed);  },  completed(todos) {    return todos.filter((todo) => todo.completed);  },};
// app Vue instanceconst app = Vue.createApp({  // app initial state  data() {    return {      todos: todoStorage.fetch(),      newTodo: "",      editedTodo: null,      visibility: "all",    };  },
  // watch todos change for localStorage persistence  watch: {    todos: {      handler(todos) {        todoStorage.save(todos);      },      deep: true,    },  },
  // computed properties  // http://vuejs.org/guide/computed.html  computed: {    filteredTodos() {      return filters[this.visibility](this.todos);    },    remaining() {      return filters.active(this.todos).length;    },    allDone: {      get() {        return this.remaining === 0;      },      set(value) {        this.todos.forEach((todo) => {          todo.completed = value;        });      },    },  },
  // methods that implement data logic.  // note there's no DOM manipulation here at all.  methods: {    pluralize(n) {      return n === 1 ? "item" : "items";    },    addTodo() {      var value = this.newTodo && this.newTodo.trim();      if (!value) {        return;      }      this.todos.push({        id: todoStorage.uid++,        title: value,        completed: false,      });      this.newTodo = "";    },
    removeTodo(todo) {      this.todos.splice(this.todos.indexOf(todo), 1);    },
    editTodo(todo) {      this.beforeEditCache = todo.title;      this.editedTodo = todo;    },
    doneEdit(todo) {      if (!this.editedTodo) {        return;      }      this.editedTodo = null;      todo.title = todo.title.trim();      if (!todo.title) {        this.removeTodo(todo);      }    },
    cancelEdit(todo) {      this.editedTodo = null;      todo.title = this.beforeEditCache;    },
    removeCompleted() {      this.todos = filters.active(this.todos);    },  },
  // a custom directive to wait for the DOM to be updated  // before focusing on the input field.  // http://vuejs.org/guide/custom-directive.html  directives: {    "todo-focus": {      updated(el, binding) {        if (binding.value) {          el.focus();        }      },    },  },});
// mountconst vm = app.mount(".todoapp");
// handle routingfunction onHashChange() {  const visibility = window.location.hash.replace(/#\/?/, "");  if (filters[visibility]) {    vm.visibility = visibility;  } else {    window.location.hash = "";    vm.visibility = "all";  }}
window.addEventListener("hashchange", onHashChange);onHashChange();

That's all

The reason of music

· One min read
Lex
Front End Engineer @ Baoxiaohe

随机播放网易歌单,听到了很久没听的歌。以前看 肖申克的救赎 对监狱里播放音乐的桥段印象深刻, 但时至今日仍无法理解音乐对于大多数人的意义。

再次听到《Valder Fields》,才明白所谓听音乐听的不是音乐本身,而是此时此刻的心境。

The setState in React

· 2 min read
Lex
Front End Engineer @ Baoxiaohe

What#

在使用 React 时,并不能通过直接修改state里的数据使页面发生更新。React 没有像 Vue 一样使用Object.defineProperty或者 Proxy 的方式来监听数据变化。所以必须通过 setState方法告知 React 数据已经发生了更改。

该方法是从 Component 继承来的,源码中有具体实现。

异步更新#

异步更新很好理解,

this.state = {  message: "Hello World"}// ...this.setState({  message: "Hello React"})console.log(this.state.message) // Hello World

虽然已经告知 React 数据更新了,log 结果仍然是更新前的 message。这就是因为setState 是非同步的。

Why is setState asynchronous#

  • 显著提高性能
  • 使props和state保持同步
每次调用 setState 方法同步调用 render 函数重新渲染页面效率是很低的,最好是在获取多次 更新后批量 `render`。

U can know more in here

How get synchronized data#

  • 1、get it in callback function
this.setState({  message: "Hello React"},() => {  console.log(this.state.message) // Hello React})
  • 2、use lifecycle function 当调用render function 执行完后会回调 componentDidUpdate这个生命周期函数。👇
componentDidUpdate() {  console.log(this.state.message) // Hello React}

了解更多lifecycle function

Must setState be asynchronous#

  • 在组件生命周期或 React 合成事件(onClick)中,setState是异步;
  • setTimeout或原生 DOM 事件中,setState是同步🕵️‍♂️
changeText() {  setTimeout(() => {    this.setState({      message: "你好呀,李银河"    })    console.log(this.state.message) // 你好呀,李银河  }, 0)}
componentDidMount() {  const btnEl = document.getElementById("btn")  btnEl.addEventListener('click',() => {    this.setState({      message: "你好呀,李银河"    })    console.log(this.state.message) // 你好呀,李银河  })}

React 源码中对这两种情况进行了判断,从而导致不同的处理方式。

数据合并#

setState函数传入对象作为参数,为什么新的对象不对旧对象完全覆盖,而只是修改了同名属性。 其实是因为源码中使用了Object.assign() 函数。

// Object.assign({},prevState,partialState)Object.assign({},this.state,{message: "你好呀,李银河"})

Why should not change state#

React 明确说明不推荐在 setState 中对 state 原数据(通常是引用类型)进行修改。 原因在于性能优化(或者 extends PureComponent)时会有问题🕵️‍♂️

shouldComponentUpdate(newProps, newState) {  // 修改相同引用类型(Array)数据并不会走下行逻辑  if(newState.books !== this.state.books){    return true   }  return false}

That's all

气场

· One min read
Lex
Front End Engineer @ Baoxiaohe

国内有个说法很有意思,当一个人表现得很自信,很有气质时,我们会形容她气场很足。区别于磁场等客观存在的物理学常识,气场是个很抽象的概念。

Don't understand it,feel it.

Why use let instead of var

· One min read
Lex
Front End Engineer @ Baoxiaohe

🆗,我相信大家都知道变量提升。like this👇

console.log(variate);let variate = 10;
Error

Uncaught ReferenceError: variate is not defined

console.log(variate); // undefinedvar variate = 10;

很好理解,因为var存在变量提升,上面的代码摇身一变:

var variate;console.log(variate); // undefinedvariate = 10;
可问题是,真实开发中谁会写这样的代码呢?因为先定义再使用变量符合正常的逻辑。仅仅为了少数可能的不正常脑回路的忍者代码似乎没必要单独加一个 let 语法。

所以,更值得探讨的是let块级作用域

Translate

· One min read
Lex
Front End Engineer @ Baoxiaohe

水平垂直居中

  position fixed  top 50%  left 50%  transform translateX(-50%)  transform translateY(-50%)

Question is this is not useful.I find some blog ,but no get the answer.

translateX 和 translateY 单独拎出来是生效的,但是一起使用却有问题。这是为什么,Oh my god。谁来拯救我。

🆗,i make it with

position fixedtop 50%left 50%transform translate(-50%,-50%)

So,u should to read MDN more( •̀ ω •́ )y